Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 560
ˈvɔlə Avatar asked Aug 30 '25 15:08

ˈvɔlə


2 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();
});
like image 179
DiplomacyNotWar Avatar answered Sep 05 '25 19:09

DiplomacyNotWar


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

like image 33
SeeSharp Avatar answered Sep 05 '25 20:09

SeeSharp