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

时间:2018-03-28 06:45:35

标签: c# appsettings serilog

我有一个自定义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

有谁知道为什么?

1 个答案:

答案 0 :(得分:0)

原因是我忘了添加WithCorrelationIds扩展方法。我认为首先实现CorrelationIdsEnricher就足够了。

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

也就是说,为了支持从我们的自定义EnricherSink的配置初始化serilog,我们不仅需要创建EnricherSink类,并实施他们的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();
}