.NET 6: how to prevent system-generated logs?

87 views Asked by At

I am using Serilog with .NET 6.0. I can set the LogLevel in appsettings.json to allow only certain type of logs.

But I need to write only the log messages explicitly written by my code.

For example: if I have set LogLevel to Information, and in the controller method I am writing one line to the Log:

logger.LogInformation(1, "Test message for Information Level.");

when it runs I can see this message in DB, but there are also other messages generated by system. I don't need that system-generated messages in my table.

How can I log the messages only written by application code?

2

There are 2 answers

0
Qiang Fu On BEST ANSWER

Set "Microsoft" logging level > Default logging level
By program.cs (Serilog.AspNetCore)

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Fatal)
    .WriteTo.Console()
    .CreateLogger();
builder.Services.AddSerilog(logger);

or appsettings.json

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Fatal"
      }
    }
  }

Logging level: Verbose-0, Debug-1, Information-2, Warning-3, Error-4, Fatal-5.

1
AnGG On

You can set the Default log level for namespaces to higher LogLevel like Error and set yours to a lower one like Debug and then you will see mainly your logs.

There is also a LogLevel that doesn't write logs at all that can be used for this case, its None in Serilog its usually 6, see link below.

In that way you can control the LogLevel for namespace, its by the prefix for example if your application namespace starts with MyApp

You can have in appsettings.json:

  "Logging": {
    "LogLevel": {
      "Default": "Error",
      "MyApp": "Debug",
      "MyApp.Controllers": "Information",
      "Microsoft": "Warning",
      "System": "Warning",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.AspNetCore.Mvc": "None"
    }
  }

Read more:

How filtering rules are applied

Log levels

Turn of logs in Serilog