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

后端 未结 2 1498
花落未央
花落未央 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();
    // ...
    

提交回复
热议问题