First of all.
You need to add these nugets:
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
Than set your serilog in appsettings.json:
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Information"
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.json",
"RollingInterval": "Day",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.log",
"RollingInterval": "Day",
"OutputTemplate": "[({Component}|{MachineName}|{ThreadId}) {Timestamp:G} [{Level:u3}]{Message:lj}{NewLine}{Exception} ]"
}
}
]
}
Than you need to add this config in C# code.
var _logger = new LoggerConfiguration()
.ReadFrom
.Configuration(configuration)
.Enrich
.FromLogContext()
.CreateLogger();
services.AddLogging(logBuilder => logBuilder.AddSerilog(_logger));
configuration is an instance of IConfiguration, u will find builder.Configuration
services --> builder.Services