Home > Blockchain >  Preventing or suppressing Microsoft log entries?
Preventing or suppressing Microsoft log entries?

Time:09-02

I'm using .NET 6 minimal APIs for a web service. I have NLog configured and working well using "appsettings.json" by using this:

builder.Services.AddLogging(loggingBuilder =>
{
    loggingBuilder.AddNLog(new NLogLoggingConfiguration(builder.Configuration.GetSection("NLog")));
});

I'm logging to a database, but I don't want the messages from Microsoft (e.g. "Microsoft.Hosting.Lifetime" and "Microsoft.AspNetCore.Hosting.Diagnostics"). There seem to be a lot of similar questions about this, but the vast majority use "NLog.config". I haven't found a solution that works using "appsettings.json". According to everything I've read, this should be trivial using a rule something like the following:

{
  "logger": "Microsoft.*",
  "finalMinLevel": "Error"
}

However this does not work for me.

The only thing I've gotten to work is to "filter in" the namespace I want, rather than filtering out the ones I don't. For example, rather than

{
  "logger": "*",
  "minLevel": "Information",
  "writeTo": "database"
}

I use

{
  "logger": "myNamespace.*",
  "minLevel": "Information",
  "writeTo": "database"
}

This is clearly not my preference.

Any ideas? Thanks in advance!

CodePudding user response:

Notice that NLog v5 introduce the following breaking change NLog.Extensions.Logging without any filter

You can explict specify RemoveLoggerFactoryFilter = false for the NLog-options-input-parameter for AddNLog. Alternative you can specify RemoveLoggerFactoryFilter for the "NLog" logger in appsettings.json. Yet another alternative is to use finalMinLevel in the NLog-Logging-Rules.

When using finalMinLevel then it is important that they are placed in top of the "rules": []-array, so they will block the LogEvents from reaching the other rule-items below.

See also https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

CodePudding user response:

The credit for this answer needs to go to Rolf. He said the order of the rules matters, and with that advice I solved my problem. My rules now look like this, and it works exactly as I'd been wanting.

"rules": [
  {
    "logger": "Microsoft.*",
    "finalMinLevel": "Warn"
  },
  {
    "logger": "*",
    "minLevel": "Information",
    "writeTo": "database"
  }
]
  • Related