asp.net-core-mvc - 如何创建从 HttpContext.TraceIdentifier 读取的 Serilog 丰富器?

标签 asp.net-core-mvc asp.net-core-1.0 action-filter serilog

我最近将 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/

相关文章:

asp.net-mvc-3 - MVC3 : Is it possible to change the result type outside of the code of the action itself?

asp.net-mvc - ASP.NET MVC 在自定义操作过滤器中查找当前用户名

c# - ASP.NET MVC Core 和 Entity Framework 中的 ToListAsync 不起作用

asp.net-core-mvc - asp.net 核心中的 AcceptVerbsAttribute

c# - 如果我的具体类除了其他接口(interface)之外还需要简单的数据类型,如何设置依赖项注入(inject)?

javascript - 如何使用 ajax post 方法将复杂对象发送到 C# Controller ?

asp.net-core - 如何根据 ASP.NET Core 中的解决方案配置运行脚本

sass - 如何从 scss 文件生成 css 文件 dotnet core

c# - .NET Core 运行时向后兼容性

c# - Razor 页面 - 尝试在 Razor 页面上实现操作过滤器