Search code examples
serilog

Queue debug log messages and dump when a error message is logged


In normal setup you only log Information and lower issues, but when an error has occurred and has been logged it's very handy when you also have the Debug log messages.

Is it currently possible to so something like this:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithCorrelationId()
    // ...other configuration...
    .CreateLogger();

normal flow:

log.Debug(...)
...
Exception:
log.Error(ex, ...)

If the minimum level is Information, queue all the Debug log messages (for example with the current CorrelationId or some other scoped variable) and when log.Error is called you can also dump the logged messages with a lower level.

Thanks

Marco


Solution

  • Serilog.Sinks.Buffer might be what you're after.

    From that README:

    Log.Logger = new LoggerConfiguration()
        .UseLogBuffer(("*", LogEventLevel.Information, LogEventLevel.Debug))
        .WriteTo(lc => lc.WriteTo.Console())
        .CreateLogger();
    

    The package uses buffer scopes rather than correlation ids to control which events are emitted when a trigger occurs:

    using (LogBuffer.BeginScope())
    {
       // ...
    }