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

时间:2019-12-09 18:40:13

标签: asp.net-core serilog

我想在每个日志条目中添加httpContextAccessor.HttpContext.TraceIdentifier,因此创建了一个自定义扩展程序,我也使用Serilog.Settings.Configuration对其进行了设置,但是不确定如何通过配置将HttpContextAccessor传递给Enricher。 >

{
    "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}"
        }
    }]
}

2 个答案:

答案 0 :(得分:1)

如果您使用Serilog.AspNetCore,则会自动包含TraceIdRequestId

Seq

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

答案 1 :(得分:0)

这个例子很好

从此存储库中获取了

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

if TG_OP = 'UPDATE' and old.jsonb_column ->> 'status' <> new.jsonb_column ->> 'status' then 
    new.jsonb_column = new.jsonb_column || jsonb_build_object('statusUpdatedTimestamp', to_char(now(), 'YYYY-MM-DD HH24-MI-SS'));
end if;
return new;