How to configure and use Serilog in ASP.NET Core 6?

Viewed 15610

Since the recently introduced new structure of the Program.cs startup code, the documentation confuses me a bit.

In the officially provided Serilog.AspNetCore example and in the Serilog.Sentry example, they use .UseSerilog() on the WebHostBuilder. I cannot find this method.

This is what I have tried:

using Serilog;

var builder = WebApplication.CreateBuilder(args);
// adding services...

builder.Logging.AddSerilog(); // <- is this even necessary?

var app = builder.Build();
app.UseSerilogRequestLogging();

// configure request pipeline
app.Run();

But how / where can I configure the sinks, e.g. Debug, Console, Sentry, ...? I have the feeling that docs are a bit outdated or I am just a bit blind.

3 Answers

You'll need to make sure you have the following packages installed:

  • Serilog
  • Serilog.Extensions.Hosting (this provides the .UseSerilog extension method. If you have the Serilog.AspNetCore package, you do not need to explicitly include this)

Then you'll need a using:

using Serilog;

Which should allow you to access .UseSerilog via builder.Host:

using Serilog;

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

You can use a different overload to get the hosting context, services, and configuration. From there you can configure sinks, etc.:

builder.Host.UseSerilog((hostContext, services, configuration) => {
    configuration.WriteTo.Console();
});

On top of Program.cs class paste the following:-

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs/rumble-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();

I used the following code snippet to fix the issue. I added it to Program.cs

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);

link

Related