0

我在 .Net 5 应用程序中使用 Serilog,我正在配置它从 .Net 加载配置appsettings.{env}.json

在这个文件中,我想为每个接收器指定一个不同的最小日志记录级别,并且我想用 a 来控制它,LevelSwitch这样我就不需要重新启动我的应用程序来更改它。为了实现这一点,我知道restrictedToMinimumLevel可以为每个接收器指定,但我找不到它由开关控制的示例。似乎它只能是具有日志记录级别的字符串,因为当我尝试将其绑定到开关时,我得到了这个异常:

System.InvalidOperationException: 'Cannot create instance of type 'Serilog.Events.LogEventLevel' because it is missing a public parameterless constructor.'

我错过了什么吗?如何设置每个接收器的最低日志记录级别,以便在运行时轻松更改而无需重新启动我的应用程序?

这些是我的设置:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "LevelSwitches": {
      "$baseSwitch": "Verbose",
      "$consoleSwitch": "Warning"
    },
    "MinimumLevel": {
      "ControlledBy": "$baseSwitch"
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          //"restrictedToMinimumLevel": "Warning",   ---> this works
          //"restrictedToMinimumLevel": {            ---> this is what I need, but doesn't work
          //  "ControlledBy": "$consoleSwitch"
          //},
          "outputTemplate": "{Timestamp} [{Level:u3}] [{LogSource}]: {Message} {Properties}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.txt"
        }
      }
    ],
    "Enrich": [
      "FromLogContext"
    ]
  }
}

我也对其他解决方案持开放态度。谢谢你。

4

1 回答 1

1

液位开关参考的名称不应带有$前缀。$前缀仅用于引用声明的液位开关

{
    "Serilog": {
        "LevelSwitches": { "consoleSwitch": "Verbose" }, <<<< No $ prefix
        "WriteTo": [
            {
                "Name": "Console",
                "Args": {
                    "levelSwitch": "$consoleSwitch" <<<<<< $ prefix
                }
            }
        ]
    }
}

此外,级别开关的参数名称必须与接收器的扩展方法中声明的名称相匹配。在控制台接收器的情况下,它被称为levelSwitch.

于 2021-10-05T14:19:47.723 回答