如何获取Serilog以使用json配置文件中的自定义浓缩器

问题描述 投票:0回答:1

我希望在我的Serilog输出中使用格式化的UTC时间戳。我编写了一个自定义增强器,当从C#代码中调用时,它可以正常工作。

public class UtcTimestampEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory pf)
    {
        logEvent.AddPropertyIfAbsent(pf.CreateProperty("UtcTimestamp", logEvent.Timestamp.UtcDateTime));
    }
}

....

var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug()
    .Enrich.FromLogContext()
    .Enrich.With(new UtcTimestampEnricher())
    .Filter
    .ByIncludingOnly( expr) // need this .Filter to ensure that 
              // Serilog.Filters.Expressions.dll gets loaded, else filters in config file get ignored
    .WriteTo.Console(
        outputTemplate: "[{UtcTimestamp:HH:mm:ss.fff} {Level:u3} {Subsystem}] {Message:lj}{NewLine}{Exception}",
        restrictedToMinimumLevel: LogEventLevel.Information);

Log.Logger = loggerConfig.CreateLogger();

现在,我希望从我的自定义json配置文件配置记录器时使用utcTimestamp扩充程序。

var jsonLogconfiguration = new ConfigurationBuilder()
    .AddJsonFile(logconfigFname)
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(jsonLogconfiguration)
    .CreateLogger();

我的json配置文件

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console"
    ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "{UtcTimestamp:yyyy,MM,dd,HH,mm,ss,fff },{Level:u3},{Subsystem},{Message:lj}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": [ "FromLogContext" , "UtcTimestampEnricher"], 
    "Filter": [
      {
        "Name": "ByIncludingOnly",
        "Args": {
          "expression": "Subsystem = 'Config'  or  Subsystem = 'Admin' "
        }
      }
    ]
  }
}

我在控制台上收到的消息:(我以前叫serilog selflog来获取有关其自身的serilog调试消息)

Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

Serilog调试输出。

2020-06-05T09:34:01.3898891Z Unable to find a method called UtcTimestampEnricher. Candidate methods are:
Serilog.LoggerConfiguration When(Serilog.Configuration.LoggerEnrichmentConfiguration, System.String, System.Action`1[Serilog.Configuration.LoggerEnrichmentConfiguration])
Serilog.LoggerConfiguration With(Serilog.Configuration.LoggerEnrichmentConfiguration, Serilog.Core.ILogEventEnricher)
Serilog.LoggerConfiguration FromLogContext(Serilog.Configuration.LoggerEnrichmentConfiguration)

我尝试使用时得到类似的输出

    "Enrich": [ "FromLogContext" , "UtcTimestamp"], 
c# configuration serilog
1个回答
0
投票

我终于弄清楚了,可以通过在C#代码中指定它来使自定义增强器起作用

var jsonLogconfiguration = new ConfigurationBuilder()
    .AddJsonFile(logconfigFname)
    .Build();

Log.Logger = new LoggerConfiguration()
    .Enrich.With(new UtcTimestampEnricher()) // is necessary
    .ReadFrom.Configuration(jsonLogconfiguration)
    .CreateLogger()

并从配置文件中删除rich with with

"Enrich": [ "FromLogContext" ],
© www.soinside.com 2019 - 2024. All rights reserved.