Serilog and async

2.7k views Asked by At

I am losing context in serilog when doing the following

public async Task<byte[]> TestAsync(TestQuery query)
{
    using (LogContext.PushProperty("CorrelationId", query.CorrelationId))
    {
        var builder = new Foo(this.logger);
        return await builder.DoSomething(query);
    }
}

When I say lose context I mean that if DoSomething continues to log then the early messages have the correlation id and the later ones don't.

If instead I do the following all is good - i.e. the correlation id appears on all downstream messages.

public async Task<byte[]> TestAsync(TestQuery query)
{
    var lgr = this.logger.ForContext("CorrelationId", query.CorrelationId);
    var builder = new Foo(lgr);
    return await builder.DoSomething(query);
}

I am happy with the latter but from one of the code samples I saw I expected the former to work.

0

There are 0 answers