Search code examples
c#.netsql-serverserilog

Specifying higher log level for serilog sink


I have a number of sinks of Serilog in my ASP.NET WEB API .NET Core 3 Application. One of the sinks is MS SQL where I'd like to write ONLY error messages. Here's a part of my appsettings.json

"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Debug", "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "Debug" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log_.txt",
          "rollingInterval": "Minute",
          "shared": true
        }
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "CONNECTIONSTRING",
          "sinkOptionsSection": {
            "tableName": "Logs",
            "schemaName": "EventLogging",
            "autoCreateSqlTable": true,
            "batchPostingLimit": 50,
            "restrictedToMinimumLevel": "Error",
            "period": "0.00:00:30"
          }
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ]
  }

But eventually I got some messages of Information and Debug level in the SQL logging table.

What's wrong with the config above? Why didn't restrictedToMinimumLevel help?

If I want to exclude message lower than Information I must set it in Default subsection of MinimumLevel section.

But in this case I'm not allowed to specify message of lower level for a particular sink. For example

"restrictedToMinimumLevel":"Debug"

won't help - debug messages won't be written into MS SQL.


Solution

  • The restrictedToMinimumLevel is the child of Args. Check the docs.

    Try:

    "WriteTo": [
      { "Name": "Console" },
      { "Name": "Debug" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log_.txt",
          "rollingInterval": "Minute",
          "shared": true
        }
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "CONNECTIONSTRING",
          "sinkOptionsSection": {
            "tableName": "Logs",
            "schemaName": "EventLogging",
            "autoCreateSqlTable": true,
            "batchPostingLimit": 50,            
            "period": "0.00:00:30"
          },
          "restrictedToMinimumLevel": "Error",
        }
      }
    ],