Search code examples
c#loggingmiddlewareserilogserilog-aspnetcore

Collection of LogContext Properties


How can I get collection of properties current LogContext in ASP.NET Core custom Middleware? I push property in Middleware like this:

var profile = context.Request.Host.Host;

using (LogContext.PushProperty("TestProp", "MyCustomProp"))
using (LogContext.PushProperty("Profile", profile))
{
  await _next(context);
}

Then I want to get the whole collection of properties, how can I do that?


Solution

  • The interface is deliberately designed not to surface such information - the information is purely for the use of Enrich.FromLogContext and subject to change. You can read the impl.

    You'll thus need to manage this externally.


    One thing that is supported common practice is to use {Properties} in your message template to render all the properties you added via:

    .Enrich.FromLogContext() 
    .WriteTo.Console("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties} {NewLine}{Exception})