Search code examples
azure-application-insightsserilogappsettingsilogger

Configure log level in .NET 7 and Serilog


Trying to figure out how to use Serilog under Microsoft Ilogger abstractions. The latter reads log level settings under the "Logger" section in appsetting.json, while Serilog reads log level settings under the "Serilog" section. Fine.

But how do they work together?

If I have code that uses the Microsoft ILogger abstractions to do the logging, I would have assumed that those abstractions would respect the settings under the "Logger" sections, further restricted by the settings under the "Serilog" section. I.e. assuming this appsettings. json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Error"
    }
  },
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information"
    }
  }
}

I would expect ILogger events to be filtered to only include Error and up, and then also filtered to only Information and up (which is a no-op in that scenario).

But that's not what I see in my tests. Instead the "Logging" section's level setting seems to be completely ignored.

I suppose that makes sense considering ILogger is an interface, which in the Serilog scenario is implemented by some class that does the logging using Serilog - no Microsoft code being executed.

But what I'm trying to do is to author a utility package that our apps can leverage to make logging to ApplicationInsights traces straightforward (avoid boilerplate code in both c# and config), and I would like to do it in such a way that (as much as possible) our apps only "see" the Microsoft logging abstractions, i.e. not really be aware that the util package uses Serilog.

But if the log levels (and other logging settings) have to reside under the "Serilog" section in appsettings.json, and also use the Serilog names (Verbose vs. Trace, MinimumLevel, vs. LogLevel...?), then Serilog will have to "shine through", doesn't it?

Is there any way that I can do this without Serilog "shinig through"?

(Note: I need to use Serilog because the ApplicationInsights provider from Microsoft doesn't support logging scopes, which we do want to use. At least according to current docs.)


Solution

  • The Logging configuration is completely controlled by Serilog, Here is how I configure,

    {
     "Serilog": {
        "MinimumLevel": "Information",
        "Override": {
          "Microsoft.AspNetCore": "Warning"
        },
        "WriteTo": [
          {
            "Name": "Console"
          }
        ]
      }
    }
    

    The override option overrides the default dotnet core setting