且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法将Serilog配置代码行转换为json配置

更新时间:2023-02-16 22:19:38

目前,Serilog不支持通过JSON应用设置配置子记录器.在github上查看此问题.

For this moment Serilog does not support configuration of sub-loggers through JSON appsettings. See this issue on github.

实际上这不是一件容易的事,因为您将 Func< LogEvent,bool> 传递给 ByInclusionOnly()过滤器.将配置数据从json文件映射到c#代码并非易事.

It's not an easy task actually because you pass Func<LogEvent, bool> to ByIncludingOnly() filter. Mapping configuration data from json file to c# code is not a trivial task.

但是,如果您仅对创建特定日志级别的子记录器感兴趣,则可以将JSON配置中的配置与 ByInclusionOnly()过滤器结合使用.

However if you are just interested in creation of sub-logger for specific log level, you could combine configuration from JSON config with ByIncludingOnly() filter.

定义将保留过滤器配置的POCO:

Define a POCO that will hold filter configuration:

public class SubLoggerConfiguration
{
    public LogEventLevel Level { get; set; }

    private string pathFormat;
    public string PathFormat
    {
        get => pathFormat;
        set => pathFormat = value.Replace("%APPLICATION_NAME%", Environment.GetEnvironmentVariable("APPLICATION_NAME"));
    }
}

在您的JSON配置中添加 SubLogger 部分:

Add SubLogger section to your JSON config:

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.RollingFile"
    ],
    "MinimumLevel": {
      "Default": "Information"
    },
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": { "pathFormat": "c:\\Logs\\log-{Date}.log" }
      }
    ],

    "SubLogger": {
      "Level": "Warning",
      "pathFormat": "Logs\\ApplicationName\\Serilog\\Warning-{Date}.log"
    } 
  }
}

将其保留在本地Serilog部分中是一个好主意,它不会破坏Serilog本身的配置.

It's a good idea to keep it inside native Serilog section, it will not break configuration of Serilog itself.

然后从配置文件中加载 SubLogger 配置:

Then load SubLogger configuration from config file:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json");
IConfiguration configuration = configurationBuilder.Build();
SubLoggerConfiguration subLoggerConfiguration = new SubLoggerConfiguration();
configuration.GetSection("Serilog:SubLogger").Bind(subLoggerConfiguration);

请注意,您必须安装 Microsoft.Extensions.Configuration.Binder NuGet软件包以将配置绑定到POCO.

Note that you have to install Microsoft.Extensions.Configuration.Binder NuGet package for binding configuration to a POCO.

现在subLoggerConfiguration将包含所需的日志级别和日志的路径格式.您可以使用此设置来调用 ByInclusionOnly()过滤器:

Now subLoggerConfiguration will contain desired log level and path format for the log. You can use this settings to call ByIncludingOnly() filter:

Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == subLoggerConfiguration.Level).WriteTo.RollingFile(subLoggerConfiguration.PathFormat));