Search code examples
c#asp.net-web-api.net-6.0serilog

What is the difference between AddSerilog and UseSerilog in .NET 6 Web API?


I'm trying to configure Serilog for a Web API project in .NET 6.

Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Configuration)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .CreateLogger();

builder.Logging.ClearProviders();

builder.Logging.AddSerilog(Log.Logger);
//builder.Host.UseSerilog(Log.Logger);

What behavior difference is there between adding Serilog to the logging pipeline and setting Serilog as the logging provider? Should I call both methods?


Solution

  • There is a huge difference. 🙂

    The .AddSerilog() provider adds a Serilog provider as one of potentially many providers. With the following configuration, the Microsoft logger will first log to the Console provider, then to the Serilog provider:

    .ConfigureLogging(logging => logging.AddConsole().AddSerilog())
    

    The .UseSerilog() configures Serilog as the only provider. The following will send all logs to Serilog regardless of whether you've configured the logging pipeline:

    .UseSerilog();
    

    The difference really boils down to using Micosoft's pluggable model or using Serilog's pluggable model.

    Typically you wouldn't use .AddSerilog() as the Serilog library is really intended to be used as the sole provider with one or more "sinks", but there may be cases where you need to log to a particular destination for which there exists a Micosoft ILogger and ILoggerProvider, but for which no Serilog sink exists (and you don't want to have to write it yourself). In such cases, you might choose to add Serilog as an additional provider.