Search code examples
asp.net-web-apiserilog

Serilog Custom Enrichers in ASP.NET Web API Pipeline


When do Serilog Custom Enrichers get executed during the Web API pipeline?

I've noticed that the method public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) is called either once or twice depending on whether or not I have a log event (i.e., Log.Debug(), Log.Warning() etc.). If I have a log event, it's called twice - both on the Http Request and HTTP response processing. If I don't have a log event, it's called only once, which is during the HTTP Response processing.


Solution

  • Serilog Enrichers run every time a call is made to write a log event to the log (as long as the event log type is enabled).

    e.g.

    Log.Information("hey1");
    Log.Warning("hey2");
    Log.Debug("hey3");
    

    Will write 3 log events to the log, which will cause all enrichers configured to be called 3 times, one for each of the events, in order to enrich each of them.

    Of course, if you have Serilog hooked up to the ASP .NET request pipeline, the ASP .NET log messages will be forwarded to Serilog, which will also cause the enrichers to be called every for every even written...