Skip Navigation

Setup Serilog in an ASP.NET 6 API

In this short article, I’ll describe how you can setup Serilog in a new .NET 6 Web API application. The documentation on Serilog’s part seems lacking to me at the moment. We’re also going to use Serilog.Settings.Configuration so we can configure Serilog via our appsettings.json.

Install your packages

Register Serilog in Program.cs

Use the .UseSerilog() extension method on builder.Host and use the provided LoggerConfiguration (lc) to use any Serilog-related configuration method you’re already used to. In this example, we want to configure Serilog using the Serilog.Settings.Configuration package to just read from our appsettings.json. So we’re going to call .ReadFrom.Configuration() and pass it the IConfiguration object provided to us by the HostBuilderContext (ctx).

using Serilog;

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, lc) => lc
    .ReadFrom.Configuration(ctx.Configuration));

// ...

Add some configuration to your appsettings.json

The following section will just enable logging to the console without anything else.

{
  /* ... */
  "Serilog": {
    "Using":  [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" }
    ]
  },
  /* ... */
}

And you’re done!

Build and start your application and your console should look something like this:

[22:30:22 DBG] Hosting starting
[22:30:22 DBG] Using development certificate: CN=localhost (Thumbprint: ...)
[22:30:22 INF] Now listening on: https://localhost:7073
[22:30:22 INF] Now listening on: http://localhost:5066
[22:30:22 DBG] Loaded hosting startup assembly GuntiNet.Api.CarPi
[22:30:22 INF] Application started. Press Ctrl+C to shut down.
[22:30:22 INF] Hosting environment: Development
[22:30:22 INF] Content root path: /project/serilog-api-sample/
[22:30:22 DBG] Hosting started