如何在参数中为自定义 Enricher 编写正确的 appsettings.json 文件

How to write the right appsettings.json file for custom Enricher within argument

我有一个自定义 Enricher:CorrelationIdsEnricher 以便将 CorrelationIdRequestId 写入日志,其构造函数有一个参数:ICorrelationContextProvider 用于传递关联上下文提供程序。

在我的项目中,我通过读取 appsettings.json 配置文件来配置 serilog。这是配置文件:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Common.Logging", "Common.Correlation" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] [{RequestId} {CorrelationId}] {Message}{NewLine}{Exception}",
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      {
        "Name": "WithCorrelationIds",
        "Args": {
          "provider": "Correlation.ServerContextProvider::Default, Common.Correlation"
        }
      }
    ],
  }
}

但是无法正确设置CorrelationIdsEnricher

有谁知道为什么?

原因是我忘了添加WithCorrelationIds扩展方法。一开始我认为实施 CorrelationIdsEnricher 就足够了。

查看 serilog-settings-configuration 的源代码 ConfigurationReader.cs 后,我发现我忘记实现扩展 WithCorrelationIds

也就是说,为了支持从我们自定义的EnricherSink的配置中初始化serilog,我们不仅需要创建EnricherSink class 还实现了他们的 LoggerSinkConfiguration 扩展。

附上CorrelationIdsEnricher实现:

using Common.Correlation;
using Serilog.Core;
using Serilog.Events;

namespace Common.Logging.Enrichers
{
    public class CorrelationIdsEnricher : ILogEventEnricher
    {
        private readonly ICorrelationContextProvider _provider;

        public CorrelationIdsEnricher(ICorrelationContextProvider provider)
        {
            _provider = provider;
        }

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var (requestId, correlationId) = GetIds();
            logEvent.AddPropertyIfAbsent(
                propertyFactory.CreateProperty("RequestId", requestId, false));
            logEvent.AddPropertyIfAbsent(
                propertyFactory.CreateProperty("CorrelationId", correlationId, false));
        }

        private (string requestId, string correlationId) GetIds()
        {
            var ctx = _provider.Context;
            return (ctx?.RequestId ?? string.Empty, ctx?.CorrelationId ?? string.Empty);
        }
    }
}

LoggerEnrichmentConfiguration扩展:

public static LoggerConfiguration WithCorrelationIds(
    this LoggerEnrichmentConfiguration enrichmentConfiguration,
    ICorrelationContextProvider provider)
{
    return enrichmentConfiguration.With(new CorrelationIdsEnricher(provider));
}

这是一个模拟的关联提供程序:

public class CorrelationContextProvider : ICorrelationContextProvider
{
    public static ICorrelationContextProvider Default { get; } = new CorrelationContextProvider();
    public ICorrelationContext Context => new CorrelationContext();
}