我有一个自定义Enricher:CorrelationIdsEnricher
以便将CorrelationId
和RequestId
写入日志,其构造函数有一个参数: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
。
有谁知道为什么?
答案 0 :(得分:0)
原因是我忘了添加WithCorrelationIds
扩展方法。我认为首先实现CorrelationIdsEnricher
就足够了。
在查看serilog-settings-configuration
的源代码ConfigurationReader.cs后,我发现忘记实施扩展程序WithCorrelationIds
。
也就是说,为了支持从我们的自定义Enricher
和Sink
的配置初始化serilog,我们不仅需要创建Enricher
和Sink
类,并实施他们的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();
}