JimmyShoe
JimmyShoe

Reputation: 2259

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 }

Upvotes: 10

Views: 10897

Answers (2)

Benya
Benya

Reputation: 189

You can use the Push method for LogContext:

ILogEventEnricher[] enrichers = 
{
    new PropertyEnricher("Address", httpContext.Connection.RemoteIpAddress),
    new PropertyEnricher("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null),
};

using (LogContext.Push(enrichers))
{
    // your code...
}

Upvotes: 18

sntr
sntr

Reputation: 96

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)) 
    { ... }

Upvotes: 8

Related Questions