Search code examples
c#serilog.net-6.0sentryilogger

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.


Solution

  • 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();
    });