Home > Enterprise >  How do I move .MinimumLevel.Override to appsettings.json?
How do I move .MinimumLevel.Override to appsettings.json?

Time:01-22

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();
    }
}

CodePudding user response:

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();

CodePudding user response:

Pass an IConfiguration to your extension and extract the value that way.

public static void AddLogging(IConfiguration configuration)
{
    var minLevelString = configuration.GetValue<string>("Logger:MinLevel");
    var minLevel = Enum.Parse<LogEventLevel>(minLevelString);
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Is(minLevel).CreateLogger();
}
  • Related