Search code examples
asp.net-coreserilog

serilog push property using multiple times


I have a serilog middleware class implemented as per this blog post https://blog.datalust.co/smart-logging-middleware-for-asp-net-core/

if i want to use LogContext.PushProperty several time to push various pieces of information in my logging do i just need to put the following code inside my Invoke method:

LogContext.PushProperty("Address", httpContext.Connection.RemoteIpAddress);
LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null);

the documentation for LogContext.PushProperty shows only adding one property and says to use a using block or do i need to do something like:

using (LogContext.PushProperty("Address", 
httpContext.Connection.RemoteIpAddress))
        using (LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null))
    {  //rest of invoke method here }

Solution

  • Here is an example https://github.com/serilog/serilog/wiki/Enrichment

    log.Information("No contextual properties");
    
    using (LogContext.PushProperty("A", 1))
    {
        log.Information("Carries property A = 1");
    
        using (LogContext.PushProperty("A", 2))
        using (LogContext.PushProperty("B", 1))
        {
            log.Information("Carries A = 2 and B = 1");
        }
    
        log.Information("Carries property A = 1, again");
    }
    

    Just use multiplay using

        using (LogContext.PushProperty("A", 2))
        using (LogContext.PushProperty("B", 1)) 
        { ... }