3

I'm using Serilog and Seq in a .net core web api to handle the logging. I've added a reference to Steve Gordon's CorrelationId Middleware to get the X-Correlation-ID from the headers (or create a new one) to update the TraceIdentifier.

I've then added another middleware class to push the correlation id into the log context, but this isn't working correctly:

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); }
    }
}

Any ideas why?

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
Nick
  • 5,616
  • 10
  • 52
  • 72
  • For a quick fix I'm just logging the TraceIdentifier as 'OriginId' instead of 'CorrelationId'. As it's only used for filtering in the logs it makes little difference – Nick Mar 08 '19 at 11:33

1 Answers1

2

It's working for me when I do the following (not as middleware):

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

So I suspect that it's your CorrelationId being overwritten by ASP.NET Core MVC as eluded to here: https://github.com/serilog/serilog-aspnetcore/issues/59

Some background to the issue and their plan to deal with it in 3.0 is also here: https://github.com/aspnet/AspNetCore/issues/5918

Apologies that this isn't a "fix", however I had the same issue and was able to work around it by adding a level of indirection between the log call (in my code) and the call to Log.Write (as shown above).

Tod Thomson
  • 4,773
  • 2
  • 33
  • 33
  • More thinking on this one... It's not perfect, as you'll get your correlation id in the cases where you call `LogWrapper.Foo(...)`, however you'll not have it on other logging that's happening pre-post your code... Will probably just have to wait until they fix this in 3.0. Apologies. – Tod Thomson Feb 19 '19 at 23:21
  • Some more info here: https://github.com/aspnet/AspNetCore/issues/9491 and here: https://github.com/stevejgordon/CorrelationId :) – Tod Thomson Sep 03 '19 at 02:32