Search code examples
c#exceptionasp.net-core-2.0serilogserilog-exceptions

asp.net core - Set Serilog.Exceptions from appsettings.json


I need to use Serilog.Exceptions package to catch exceptions. Serilog is read from appsettings.json

{
    "Serilog": {
        "Using": [
            "Serilog.Sinks.RollingFile",
            "Serilog.Sinks.Seq"
        ],
        "WriteTo": [
            {
                "Name": "RollingFile",
                "Args": {
                    "restrictedToMinimumLevel": "Debug",
                    "pathFormat": "myPath\\log-{Date}.log"
                }
            },
            {
                "Name": "RollingFile",
                "Args": {
                    "restrictedToMinimumLevel": "Error",
                    "pathFormat": "myPath\\error-{Date}.log"
                }
            },
            {
                "Name": "Seq",
                "Args": {
                    "serverUrl": "myUrl",
                    "apiKey": "myApiKey"
                }
            }
        ],
        "Enrich": [
            "FromLogContext",
            "WithMachineName",
            "WithThreadId"
        ],
        "Properties": {
            "Application": "myApplicationName"
        }
    }
}

And in my startup.cs

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

Log.Logger = logger;

But it doesn't work. Do I need to add some other properties in appsettings.json for Serilog.Exceptions package? Or is the appsettings.json configure correctly? What am I doing wrong? Thanks


Solution

  • The following is how I setup Serilog in ASP.NET Core 2.1. You can take it as checklist and see what you have missed.

    1. Install packages from Nuget: Serilog.AspNetCore, Serilog.Exceptions, Serilog.Settings.Configuration and other sinks you want to use.
    2. Setup Serilog in your main program:

      public class Program
      {
          public static void Main(string[] args)
          {
              CreateWebHostBuilder(args).Build().Run();
          }
      
          public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
              WebHost.CreateDefaultBuilder(args)
                  .UseStartup<Startup>()
                  .UseSerilog((hostingContext, loggerConfiguration) => 
                      loggerConfiguration
                          .ReadFrom.Configuration(hostingContext.Configuration)
                  );
      }
      
    3. Put WithExceptionDetails in your Serilog section in appsettings.json:

      {
          "Serilog": {
              ...
              "Enrich": [
                  "FromLogContext",
                  "WithExceptionDetails"
              ],
              ...
          }
      }