Search code examples
c#.netloggingserilog

How do I move .MinimumLevel.Override to appsettings.json?


Is there a way to move the MinimumLevel overrides to appsettings.json?

Sometimes I don't want to display the system logs, so I do

.MinimumLevel.Override("System", LogEventLevel.Error)
.MinimumLevel.Override("Microsoft", LogEventLevel.Error)

and sometimes I want to keep an eye on the requests for debugging purposes:

.MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Debug)
.MinimumLevel.Override("Microsoft.AspNetCore.Routing.EndpointMiddleware", LogEventLevel.Debug)

So is there a better way to do that in appsettings.json?

public static class LoggingExtensions
{
    public static IHostBuilder AddLogging(this IHostBuilder builder, LogEventLevel minLevelLocal = LogEventLevel.Information)
    {
        const string outputTemplate = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}";

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Is(minLevelLocal)
            .MinimumLevel.Override("System", LogEventLevel.Error)
            .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
            // .MinimumLevel.Override("Microsoft.AspNetCore.Hosting", LogEventLevel.Debug)
            // .MinimumLevel.Override("Microsoft.AspNetCore.Routing.EndpointMiddleware", LogEventLevel.Debug)
            .Enrich.FromLogContext()
            .Enrich.WithMachineName()
            .Enrich.WithProcessName()
            .Enrich.WithMemoryUsage()
            .WriteTo.Console(outputTemplate: outputTemplate)
            .CreateLogger();

        return builder.UseSerilog();
    }
}

Solution

  • The documentation for the Serilog.Settings.Configuration library has explicit support for this.

    "Serilog": {
      "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
        }
      }
    }
    

    And to tell it to read the config from there:

    var logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();