Serilog:如何在配置文件中指定过滤器表达式

Serilog : how do you specify a filter expression in config file

我正在尝试在应用程序设置中指定此过滤器。json 文件

.Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.Hosting.Internal.WebHost"))

以上语法在 c#

中指定时有效

但是尝试在 json 文件中指定相同内容是行不通的。

"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "Matching.FromSource = 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
}
}

您需要为此使用 Serilog.Expressions

Install-Package Serilog.Expressions

appsettings.json 中的过滤器部分如下所示:

"Filter": [
  {
    "Name": "ByExcluding",
    "Args": {
      "expression": "SourceContext = 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
    }
  }
],

在这种特定情况下,我建议考虑 level overrides 作为替代方案,这样可以更有效地关闭特定命名空间。

Nicholas Blumhardt 的回答是正确的,但还有一些额外的细节可能对您有用。 如果你没有如下一段源码(serilog初始化时)

.Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.Hosting.Internal.WebHost"))

在你的一个 .cs 文件中,那么 Serilog.Filters.Expressions.dll 文件将不会被加载,并且你的过滤器表达式将在加载配置文件时静默失败。所以一定要在你的 .cs 源中引用 .Filter(即使它从未被调用)

另一个对调试 serilog 本身很有用的项目(尤其是像这个例子这样的配置文件启动)是将 serilog 本身的调试添加到控制台

   // this is just to check on serilog startup and configuration, problems with serilog itself get written to console
    Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

然后 运行 您的 .cs 应用处于调试模式,并在您从其配置文件初始化 serilog 时检查控制台上的消息。

使用 Filter.ByIncludingOnly 您的 "MyWellKnownNamespace" 更容易 这比试图找出不需要的消息来自哪个命名空间要容易得多:

 Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(_configuration)
                .Filter.ByIncludingOnly( Matching.FromSource("MyWellKnownNamespace") )
                .CreateLogger();