11

Trying to set minimum log level for Serilog 2.8.0 (in .NET 4.6.2). Logging is working fine, but not the Override feature.

Here is my Program.cs:

using System;
using LogTest1.Classes;
using Microsoft.Extensions.Configuration;
using Serilog;
using SomeLib;


namespace LogTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", false, true)
                .Build();

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

            Log.Verbose("Verbose");
            Log.Debug("Debug");
            Log.Information("Information");
            Log.Warning("Warning");
            Log.Error("Error");
            Log.Fatal("Fatal");

            Console.ReadKey();
        }
    }
}

And the appsettings.json file:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": {
      "Default": "Warning",
      "Override": {
        "LogTest": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" }
    ]
  }
}

Expected to see all the logs, starting from Information, but instead got only from Warning.

C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
Kristian Sik
  • 123
  • 1
  • 1
  • 6

1 Answers1

20

You are overriding the MinimumLevel only for log messages sent from a SourceContext with the name LogTest, as per your configuration....

"Override": {
  "LogTest": "Information"
}

A simple call to Log.Information("Information") like you're doing will not have the source context set, therefore the override doesn't apply... You have to create the context first.

var contextLog = Log.ForContext("SourceContext", "LogTest");
contextLog.Information("This shows up because of the override!");
contextLog.Information("... And this too!");

Log.Information("This does **not** show, because SourceContext != 'LogTest'");

You can read more about SourceContext in the documentation: https://github.com/serilog/serilog/wiki/Writing-Log-Events#source-contexts

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • 2
    Also make sure that you have added the needed nugets: ```Serilog.Settings.Configuration``` and ```Serilog.Settings.AppSettings``` – Kraego Sep 02 '21 at 08:42