Is it possible to elegantly configure Serilog with if-statements?

后端 未结 2 1499
花落未央
花落未央 2020-12-18 06:39

My Serilog configuration code looks like this:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .Enrich.FromLogContext()
    .Mi         


        
相关标签:
2条回答
  • 2020-12-18 07:06

    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();
    // ...
    
    0 讨论(0)
  • 2020-12-18 07:09

    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>
    
    0 讨论(0)
提交回复
热议问题