簡體   English   中英

如何讓 Serilog 使用 json 配置文件中的自定義濃縮器

[英]How to get Serilog to use custom enricher from json config file

我希望在我的 Serilog output 中使用格式化的 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 調試 output。

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)

當我嘗試使用時,我得到了類似的 output

"Enrich": [ "FromLogContext" , "UtcTimestamp"], 

即使問題已經解決,我也想分享我關於這個問題的 2 美分。

每當您創建自定義Enricher時,您有兩個選擇如何注冊它:

  • 通過代碼
  • 或通過配置

通過代碼

豐富者

public class UtcTimestampEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory pf)
    {
      ...
    }
}

登記

Log.Logger = new LoggerConfiguration()
    .Enrich.With<UtcTimestampEnricher>()
    .CreateLogger()

通過配置

豐富者

public class UtcTimestampEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory pf)
    {
      ...
    }
}

注冊助手

public static class LoggingExtensions
{
    public static LoggerConfiguration WithUtcTimestamp(
        this LoggerEnrichmentConfiguration enrich)
    {
        if (enrich == null)
            throw new ArgumentNullException(nameof(enrich));

        return enrich.With<UtcTimestampEnricher>();
    }
}

登記

{
  "Serilog": {
    ...,
    "Using": [ "Your.Assembly.Name" ],
    "Enrich": [ "FromLogContext", "WithUtcTimestamp" ]
  },

因此,正如您所看到的,在基於配置的設置的情況下,您需要注冊的是注冊幫助器方法(而不是豐富器本身)。

我終於想通了,並且可以通過在 C# 代碼中指定自定義濃縮器來工作

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

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

並從配置文件中刪除豐富

"Enrich": [ "FromLogContext" ],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM