asp.net-coreloggingserilogseqseq-logging

after await next when I try to use serilog LogContext it doesn’t push any property to log messages


While setting everything for Serilog and SEQ I was stuck in an issue that you may have an answer for it. I am trying to add some properties to all logs using LogContext.PushProperty. However, in my middleware(see image below) the LogContext can push property to logs before await next.Invoke(). While after await next when I try to use LogContext it doesn’t push any property to log messages. The issue is that claims are always empty before the await next.Invoke() and they only have values after await next so I am forced to use LogContext after the await but it doesn’t work there as mentioned. Please advise if you have a clue?

Thanks,

enter image description here


Solution

  • LogContext needs to be used in conjunction with a using block, covering the whole scope in which you want the property to be available. You may need something like:

    IDisposable popContext = null;
    
    var user2 = context.User as IAMClaimsUser;
    if (user2 != null && !string.IsNullOrEmpty(user2.FirstName))
    {
        popContext = LogContext.PushProperty("UserEmail", user2.Email);
    }
    
    using (popContext)
    {
        // `UserEmail` will be attached to events logged in this block
        await next();
    }