Search code examples
serilog

Serilog LoggerConfiguration equivalent of AddFilter with log level


My current code is like this:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) 
{
    return WebHost.CreateDefaultBuilder(args)
      .ConfigureLogging((hostingContext, logging) => {
          logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
          logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);
      })
      .UseSerilog(Log.Logger)
}

I now get deprication error:

warning CS0618: 'SerilogWebHostBuilderExtensions.UseSerilog(IWebHostBuilder, ILogger, bool, LoggerProviderCollection)' is obsolete: 'Prefer UseSerilog() on IHostBuilder'

My understanding is I need to now create the logger like this:

public static void Main(string[] args) {
    Log.Logger = new LoggerConfiguration()
    // set filters ???
    .CreateLogger();

and then just have UseSerilog() in CreateWebHostBuilder

But how do I set equivalent filters in LoggerConfiguration ? I can't seem to find relevant examples.


Solution

  • That error is telling you to move away from Microsoft.AspNetCore.Hosting.IWebHostBuilder to Microsoft.Extensions.Hosting.IHostBuilder.

    IWebHostBuilder is for .NET Core 2, see the documentation.

    Your code would look like below.
    (Also renamed that method.)

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
          .ConfigureLogging((hostingContext, logging) => {
              logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
              logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);
        })
        .UseSerilog(Log.Logger);
    }
    

    If you can't migrate, you'll have to pick an older version of Serilog.