覆盖 MinimumLevel 在 Serilog 中不起作用

Overriding MinimumLevel doesn't work in Serilog

正在尝试为 Serilog 2.8.0(在 .NET 4.6.2 中)设置最低日志级别。日志记录工作正常,但覆盖功能不正常。

这是我的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();
        }
    }
}

appsettings.json文件:

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

预期会看到所有日志,从 信息 开始,但只从 警告.

开始

根据您的配置,您正在覆盖 MinimumLevel 用于从名称为 LogTestSourceContext 发送的日志消息。 ...

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

像您所做的那样对 Log.Information("Information") 的简单调用不会设置源上下文,因此覆盖不适用...您必须先创建上下文。

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'");

您可以在文档中阅读有关 SourceContext 的更多信息: https://github.com/serilog/serilog/wiki/Writing-Log-Events#source-contexts