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