Search code examples
c#asp.net-coreserilog

Add Specfic Namespace to appsettings.json - Serilog ASP.NET Core 3.1


I followed a tutorial that gets you to set all the Serilog config up in appsettings.json; however, I cannot get my WebAppLogger.Startup to output any messages:

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Warning",
      "WebAppLogger.Startup": "Verbose",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { 
        "Name": "Console",
        "Args": {
          "outputTemplate": "{Timestamp:G} {Level} {Message}{NewLine:1}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.txt",
          "outputTemplate": "{Timestamp:G} {Level} {Message}{NewLine:1}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.json",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      }
    ]
  }
}

I have tried adding "Using": [{"WebAppLogger.Startup": "Verbose"}] but this crashes the app.

I have found nothing on the Serilog docs that relates to using appsettings.json.

Also, is there a way I can completely suppress the Microsoft and System messages?


Solution

  • In the Using field of the appsettings.json, you have to specify the sinks that you'll be using.

    For example, if you're writing to the Console, you should specify the full name of the class including the namespace (in this case Serilog.Sinks.Console), provided that you installed the NuGet package of the sink, of course.

    e.g.:

    {
      "Serilog": {
        "Using":  ["Serilog.Sinks.Console"], // <<<<<<<<<<##############
        "MinimumLevel": "Debug",
        "WriteTo": [
          { "Name": "Console" }
        ],
        "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
      }
    }
    

    You can see examples in the GitHub repository:


    You can supress Microsoft and System messages by using Filters (e.g. ByExcluding, ByIncluding). In the sample of the Serilog.Settings.Configuration repo there's an example of how to configure it via appsettings.json.