serilog-contrib / SerilogSinksInMemory

In-memory sink for Serilog to use for testing
MIT License
53 stars 7 forks source link

Missing enriched properties. #11

Closed xavierjohn closed 3 years ago

xavierjohn commented 3 years ago

Memory sink is great for testing and I was trying it out with ASP.NET Core 5 but I am not able to find enriched properties. How do I get enriched properties? I was trying to verify if the log has correlationid passed via the header.

I have setup logging in the test as

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Error()
                .WriteTo.InMemory()
                .WriteTo.File(new CompactJsonFormatter(), @"c:\temp\foo.log")
                .CreateLogger();

Then make a http call using the WebApplicationFactory fixture.

My startup.cs has httpcontext enriched.

            app.UseSerilogRequestLogging(options =>
            {
                options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                {
                    diagnosticContext.Set("CorrelationId", GetCorrelationId(httpContext));
                };
            });

The text log has the correlation ID in it like "CorrelationId":["something"] but I am not able to verify it using InMemory test.

sandermvanvliet commented 3 years ago

Hi @xavierjohn!

Good to hear you find it useful!

For enriched properties to show up on the InMemorySink (and any other sink in fact) you will need to instruct the logger to do the enrichment.

Normally you would do something like this:

Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Error()
                .Enrich.FromLogContext() // Add this bit
                .WriteTo.InMemory()
                .WriteTo.File(new CompactJsonFormatter(), @"c:\temp\foo.log")
                .CreateLogger();

and then when you have logging call like so:

using(LogContext.PushProperty("Name", "bob"))
{
    Log.Logger.Information("Hello, world!");
}

then in the assertion you can do this:

InMemorySink.Instance
    .Should()
    .HaveMessage("Hello, world!")
    .Appearing.Once()
    .WithProperty("Name")
    .WithValue("bob");

I'm not sure exactly how EnrichDiagnosticContext sets this up so you may need to check the documentation there on how to add the proper Enrich.FromLogContext() type call to the LoggerConfiguration.

Hope that helps!

xavierjohn commented 3 years ago

I will add .Enrich.FromLogContext() and give it a try today. Given the text log already has all the properties makes me feel the problem is something else.

sandermvanvliet commented 3 years ago

Do you perhaps have a small repro case that I could have a look at?

xavierjohn commented 3 years ago

You are correct. I confused CorrelationId with RequestId. It all works as expected. Full sample at https://github.com/xavierjohn/WeatherForcastWithAuth/blob/50a63648eab9936e0397a888a4759e5e0d667b4e/tests/DiagnosticControllerTests.cs#L58

Thanks a lot for the information.