Search code examples
.net-6.0serilog

Add Serilog LogContext to every log call


Is there a way to "inject" LogContext call to all the Serilog log calls in a project? I'd like to add an ExecutionContext property, which is just a hex string generated in a shared class library. I'm using Serilog with Microsoft.Extensions.Logging, and also using Serilog Request Logging in Asp.Net Core API project.


Solution

  • Yes you can implement ILogEventEnricher Interface to do that like this event will fires on every log event an in application.

    public class PropertyBagEnricher : ILogEventEnricher
        {
           
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
               logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(your key, your Value));
                }
            }