appsettings.json 中 Filters.Expressions 的 Serilog 和过滤器

Serilog and Filters from Filters.Expressions in appsettings.json

我们想要获取日志:

  1. 控制台(所有日志)
  2. 文件(所有日志)
  3. 文件(仅过滤日志

所有这些都在 appsettings.json 中配置。

这是应用程序的 appsettings.json 文件:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Literate", "Serilog.Sinks.File", "Serilog.Filters.Expressions" ],
    "MinimumLevel": "Verbose",
    "WriteTo": [
      {
        "Name": "LiterateConsole"
      },
      {
        "Name": "File",
        "Args": {
          "path": "%TEMP%\Logs\FileWithoutFilter-.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
          "rollingInterval": "Day"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "%TEMP%\Logs\UPLOADERROR-.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        },
        "Filter": [
          {
            "Name": "ByIncludingOnly",
            "Args": {
              "expression": "@Level = 'Error' and UploadError is not null"
            }
          }
        ]
      }
    ]
  }
}

但是,尽管控制台和文件(无过滤)运行 很好,但带过滤的文件正在记录所有行,就像文件(无过滤)一样。

我们正在用 C# 代码发送 log.error 行:

Log.Error("Fichero con error {@UploadError}", true);

但是,我说过,所有行都记录到 UPLOADERROR 文件

知道 appsettings.file 有什么问题吗?

此致。

解决方案是使用带有 serilog 的子记录器。然后,您必须使用过滤和接收器配置子记录器。

仔细阅读与常规、配置和过滤器相关的 serilog 文档是诀窍。

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Literate", "Serilog.Sinks.File", "Serilog.Filters.Expressions" ],
    "MinimumLevel": "Verbose",
    "WriteTo": [
      {
        "Name": "LiterateConsole"
      },
      {
        "Name": "File",
        "Args": {
          "path": "%TEMP%\Logs\FileWithoutFilter-.log",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
          "rollingInterval": "Day"
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "@Level = 'Error' and UploadError is not null"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "%TEMP%\Logs\UPLOADERROR-.log",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ]
          }
        }
      }
    ]
  }
}

使用之前的配置,现在一切正常。