8

There is documentation for "globally" overriding MinimumLevel in code, xml and json.

But can I override for a specific sink, using appsettings.json? For example, I want to log at warning level for class MyClass, but only for the console sink.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • Your first stop for such questions should be the [ASP.NET Core Documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#configuration) and [Filter Rules](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#create-filter-rules-in-configuration) as its well documented on how to set per class/namespace logging level – Tseng Aug 13 '18 at 08:54
  • 2
    @Tseng Those examples are for the built in logging. I'm using Serilog. – lonix Aug 13 '18 at 09:04
  • As long you plug it in with the `ILoggerFactory` and use `ILogger` in your classes, it will be applied to it too. See https://github.com/serilog/serilog-aspnetcore. `ILoggerFactory` and `ILogger` are abstractions and the logging config works for all of that one which implement/are based on these abstractions – Tseng Aug 13 '18 at 09:05

2 Answers2

10

Just use the restrictedToMinimumLevel param in the config section of the specific sink:

{
  /* .. */
  "Serilog": {
    "MinimumLevel": {
      "Default": "Verbose", /* <-- set the default level to the LOWEST applicable for your app  */
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console",
          "restrictedToMinimumLevel": "Information" /* <-- set the minimum level for specific sink  */
        }
      },
      {
        "Name": "File",
        "Args": {
          /* .. */
          "restrictedToMinimumLevel": "Warning" /* <-- set the minimum level for specific sink  */
        }
      },
      {
        "Name": "Udp",
        "Args": {
          /* .. */
          "restrictedToMinimumLevel": "Warning" /* <-- set the minimum level for specific sink  */
        }
      }
    ],
    /* .. */
  }
}
vladimir
  • 13,428
  • 2
  • 44
  • 70
1

I am interested in this question too. I can't find a solution. Apparently this cannot be done on correct.It can turn out like this:

  1. Create two sections of SERILOG (Serilog and Serilog2 or SerilogLow)
  2. configure the minimum logging level for each partition individually
  3. to register for both sections.

List item

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    var logger = new LoggerConfiguration().ReadFrom.ConfigurationSection(_configuration.GetSection("Serilog"))
    .ReadFrom.ConfigurationSection(_configuration.GetSection("SerilogLow")).CreateLogger();
    services.AddSingleton<ILogger>(logger);
}

HTH