Serilog middleware excludes userid from error messages, anyone know why?

305 Views Asked by At

I wrote a small serilog middleware that I'd like to capture the user id from the httpcontext and include it in log files. It works for normal logs, but not for unhandled exceptions. This is for .net core. Anyone know why?

Thank you!

 public class SerilogUserIdLogger
{
    readonly RequestDelegate _next;

    public SerilogUserIdLogger(RequestDelegate next)
    {
        if (next == null) throw new ArgumentNullException(nameof(next));
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.User != null && httpContext.User.Identity != null && httpContext.User.Identity.IsAuthenticated)
        {
            var userId = httpContext.User.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
          
            using (LogContext.PushProperty("UserId", userId))
            {
                await _next(httpContext);
            }
        }
        else
        {
            await _next(httpContext);
        }
    }
}




  app.UseMiddleware<SerilogUserIdLogger>();
1

There are 1 best solutions below

1
On

Probably because the exception is being caught and logged in an earlier middleware. So, by the time the exception is logged, your log context property has already been popped.

What you really want to do is to capture the log context at the time the exception is thrown and then apply it at the time it is logged. This library is one (Serilog-specific) way to achieve that, and I have a similar library that works with any .NET logger provider.