Is it possible to elegantly configure Serilog with if-statements?
Serilog 2.9.0 introduces conditional sinks. Using .WriteTo.Conditional
you specify the condition that defines if the sink will be written to or not.
e.g.
bool enableConsoleLogging = ...
bool enableFileLogging = ...
var builder = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.Enrich.FromLogContext()
.MinimumLevel.Warning()
.WriteTo.Conditional(evt => enableConsoleLogging, wt => wt.Console())
.WriteTo.Conditional(evt => enableFileLogging, wt => wt.File(...));
Log.Logger = builder.CreateLogger();
// ...
I think to make it elegant and still do it in code, you do have to extend the API and create your own extension methods that encapsulate the condition checks and update the builder with the correct sink and parameters.
Something like
Log.Logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.Enrich.FromLogContext()
.MinimumLevel.Warning()
.WriteToConsoleIfEnabled() // <---
.WriteToFileIfEnabled() // <---
.CreateLogger();
On a different note, have you considered using Serilog.Settings.AppSettings
or Serilog.Settings.Configuration
instead? The configuration in code gets much cleaner, and you can add/remove sinks in the configuration file as you wish...
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger()
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="serilog:minimum-level" value="Verbose" />
<add key="serilog:using:Console" value="Serilog.Sinks.Console" />
<add key="serilog:write-to:Console" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:RollingFile.pathFormat" value="C:\myapp-{Date}.txt" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />
<!-- //etc... -->
</appSettings>
</configuration>