Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
user246392 Avatar asked Sep 10 '25 22:09

user246392


1 Answers

NOTE THIS ANSWER IS NOW OUT OF DATE
Refer to the answer below from @MikeHaas for latest version of Serilog

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.

like image 97
Derek Greer Avatar answered Sep 13 '25 13:09

Derek Greer