我最近将 Serilog 集成到了几个 .NET Standard 类库中,包括 MVC 6 项目使用的一些类库。我想做的是使用 HttpContext.TraceIdentifier 丰富日志条目。我编写了一个操作过滤器,将 HttpContext.TraceIdentifier
设置为 Correlation-ID
请求 header 值(如果存在):
public override void OnActionExecuting(ActionExecutingContext context)
{
StringValues correlationIds;
Guid correlationId;
if (!context.HttpContext.Request.Headers.TryGetValue(Constants.CorrelationIdHeaderName, out correlationIds) || correlationIds.Count != 1 || !Guid.TryParse(correlationIds[0], out correlationId))
{
correlationId = _guidFactory.Random();
context.HttpContext.Response.Headers.Add(Constants.CorrelationIdHeaderName, correlationId.ToString("D"));
}
context.HttpContext.TraceIdentifier = correlationId.ToString("D");
base.OnActionExecuting(context);
}
问题是,如何让 Serilog 在此请求的生命周期内了解相关 ID?由于它似乎没有 HttpContext.Current
属性,因此我不确定如何创建一个可以工作的丰富器。这可能吗?
最佳答案
我认为您不需要为此使用丰富器。
将 {RequestId}
放入接收器的 outputTemplate
中会得到一个类似“0HL0GJPLR7AOD”的 ID。如果我在记录某些内容之前设置 HttpContext.TraceIdentifier
,那么 {RequestId}
会准确地为我提供该 ID,因此自定义 ID 也适用于 {RequestId}
。
我认为 {RequestId}
是一个 Microsoft.Extensions.Logging 功能,但它可以与 serilog 一起开箱即用(至少当您使用 Serilog.Extensions.Logging 时)。
更新:不要忘记配置Enrich.FromLogContext()
。
关于asp.net-core-mvc - 如何创建从 HttpContext.TraceIdentifier 读取的 Serilog 丰富器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184786/