Search code examples
c#.net.net-coreserilog

Serilog MinimumLevel Override is not working


{
"Logging":{
  "LogLevel":{
    "Default": "Warning",
    "System.Net.Http.HttpClient.SomeClassLibraryName": "Error"
   }
  }
}

If I add the above code in my app settings then the logs for above-provided namespace only get written for the error and it works.

But when I try to achieve the same thing using the logging configuration for Serilog in .NET 6 WEB API it does not work. This is the method of which I am calling for setting the log configuration :

public static void LoggingConfiguration()
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .MinimumLevel.Override("System.Net.Http.HttpClient.SomeClassLibraryName", LogEventLevel.Error)
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .MinimumLevel.Override(SomeClassLibraryName, LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Async(c => c.File("Logs/Log.txt", rollingInterval: RollingInterval.Day))
        .WriteTo.Async(c => c.Console())
        .CreateLogger();
}

I have tested this code for Microsoft and by changing the minimum level from information to warning and error, it works for them but is not working for a specific case.

I have explored the following options so far but did not find any satisfactory results.

https://github.com/serilog/serilog/wiki/Writing-Log-Events#source-contexts

https://github.com/serilog/serilog/issues/1390

https://github.com/serilog/serilog-extensions-logging/issues/177


Solution

  • You should rely on built-in registration like here.

    Try moving the registration to builder like so:

    var builder = WebApplication.CreateBuilder();
    builder.Logging.SetMinimumLevel(LogLevel.Warning);
    

    or

    var builder = WebApplication.CreateBuilder();
    builder.Logging.AddFilter("System.Net.Http.HttpClient.ClassLibraryName", LogLevel.None);