Serilog is one of the most popular logging libraries. This tutorial will show you how to set it up for an AspNetCore project.

Serilog.AspNetCore

Install Nuget Package Serilog.AspNetCore. It is the recommended nuget package to configure Serilog for AspNetCore projects.

Add JSON Configuration

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "System": "Information",
        "Microsoft": "Information",
        "Microsoft.AspNetCore": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Logs\\serilog-setup.txt",
          "rollingInterval": "Day",
          "outputTemplate": "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}

This sample configuration asks Serilog to use file logging. To learn more about Serilog configuration, please read this doc. For json configuration syntax, please refer to Serilog.Settings.Configuration. You can find a more advanced sample here.

Load JSON Configuration

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile($"appsettings.{environment}.json", true)
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();

Refer to Program.cs.

Log HostBuilder Exceptions

try
{
    CreateHostBuilder(args).Build().Run();
}
catch (Exception e)
{
    Log.Fatal(e, "Host terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

Refer to Program.cs.

Use Serilog Middleware

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .UseSerilog();

Refer to Program.cs.

Do Not Use Serilog Request Logging Middleware

app.UseSerilogRequestLogging();

This is suggested in the document. Although it offers some benefits, it also causes the unhandled exceptions being logged twice. Until it is fixed, I don’t suggest using it.