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

后端 未结 2 1508
花落未央
花落未央 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: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()
    

    
    
      
        
    
        
        
    
        
        
        
    
        
      
    
    

提交回复
热议问题