如何通过配置将 IHttpContextAccessor 传递给 Serilog Enricher

How to pass IHttpContextAccessor to Serilog Enricher by Configuration

我想将 httpContextAccessor.HttpContext.TraceIdentifier 添加到每个日志条目,因此创建了一个自定义增强器,我还使用 Serilog.Settings.Configuration 设置了它,但不确定如何通过配置将 HttpContextAccessor 传递给增强器

{
    "Enrich": ["FromLogContext", "LogTraceid"],
    "WriteTo": [{
        "Name": "File",
        "Args": {
            "path": "App_Data/Logs/App.log",
            "rollingInterval": "Day",
            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] [{TraceId}] [{RequestId}] {Message}{NewLine}{Exception}"
        }
    }]
}

如果您使用 Serilog.AspNetCoreTraceIdRequestId 将自动包含在内。

查看代码示例:https://github.com/serilog/serilog-aspnetcore/tree/dev/samples

这个例子工作正常

从这个 repo 得到它

https://github.com/JohnLTaylor/Serilog.Enrichers.TraceIdentifier/blob/master/src/Serilog.Enrichers.TraceIdentifier/Enrichers/TraceIdentifierEnricher.cs

class TraceIdentifierEnricher : ILogEventEnricher
{
    private const string TraceIdentifierPropertyName = "TraceIdentifier";
    private readonly IHttpContextAccessor _contextAccessor;

    public TraceIdentifierEnricher() : this(new HttpContextAccessor())
    {
    }

    public TraceIdentifierEnricher(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var property = propertyFactory.CreateProperty(TraceIdentifierPropertyName, _contextAccessor.HttpContext?.TraceIdentifier ?? "-");
        logEvent.AddOrUpdateProperty(property);
    }
}

public static class TraceIdentifierLoggerConfigurationExtensions
{
    public static LoggerConfiguration WithTraceIdentifier(
       this LoggerEnrichmentConfiguration enrichmentConfiguration)
    {
        if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
        return enrichmentConfiguration.With<TraceIdentifierEnricher>();
    }
}

还要确保您已在服务集合

中注册IHttpContextAccessor
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    ...
}