This is my approach for Serilog.Sinks.File
and Serilog.Settings.Configuration
. It's an evolution of the accepted answer, but also using an appsettings.json
.
Sample of the appsettings.json
:
"Serilog": {
"Using": [ "Serilog.Sinks.Debug", "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": {
"DebugSink": "Debug",
"FileSink": {
"Name": "File",
"Args": {
"path": "%LOCALAPPDATA%/Company/Application/{timestamp}.log"
}
}
}
}
Please look at how I handle array declaration in the WriteTo
- it is on purpose to have an easier to replace a {timestamp}
placeholder — details about WriteTo
can find in this section.
Now, let's configure the logger using the config from appsettings.json
:
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
const string serilogFileSinkPath = "Serilog:WriteTo:FileSink:Args:path";
if (configuration.GetSection(serilogFileSinkPath).Exists())
{
var filePath = configuration[serilogFileSinkPath];
configuration[serilogFileSinkPath] = filePath.Replace("{timestamp}", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
}
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
The code reads the configuration.
Next, it checks if the given section that contains the file path is present - if yes, then the replacement of the placeholder happens.
Now configuration has all the needed data, so it can be used to configure the logger.