3

我在 .net 核心 web api 中使用 Serilog 和 Seq 来处理日志记录。我添加了对 Steve Gordon 的CorrelationId 中间件的引用,以从标题中获取 X-Correlation-ID(或创建新的)以更新 TraceIdentifier。

然后,我添加了另一个中间件类以将相关 ID 推送到日志上下文中,但这无法正常工作:

public class LogCorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    public LogCorrelationIdMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        // doesn't work - blank CorrelationId in Seq
        using (LogContext.PushProperty("CorrelationId", context.Request.HttpContext.TraceIdentifier)) { return _next(context); }

        // works - correct CorrelationId2 in Seq 
        //using (LogContext.PushProperty("CorrelationId2", context.Request.HttpContext.TraceIdentifier)) { return _next(context); }
    }
}

任何想法为什么?

4

1 回答 1

2

当我执行以下操作(而不是作为中间件)时,它对我有用:

using (LogContext.PushProperty("CorrelationId", "This is a test..."))
{
    Log.Write(level, exception, messageTemplate, propertyValues);
}

所以我怀疑这是你CorrelationId被 ASP.NET Core MVC 覆盖的问题,因为这里没有解决: https ://github.com/serilog/serilog-aspnetcore/issues/59

该问题的一些背景以及他们处理它的计划3.0也在这里: https ://github.com/aspnet/AspNetCore/issues/5918

很抱歉这不是一个“修复”,但是我遇到了同样的问题并且能够通过在日志调用(在我的代码中)和对 Log.Write 的调用之间添加一个间接级别来解决它(如上所示)。

于 2019-02-19T06:59:50.893 回答