Search code examples
c#loggingseriloggetseqseq-logging

How to customize exception output using serilog


I'm using Serilog as my logging framework (with Seq as my log sink). When logging exceptions I'm using something like:

log.Error(ex, "Operation Failed");

My application makes heavy use of async/await methods. When unhandled exceptions occur the stack traces are very hard to read. There is a nuget package that cleans up async stack traces (https://github.com/aelij/AsyncFriendlyStackTrace). This creates an extension method to give you access to a modified/clean stack trace:

ex.ToAsyncString()

I'd like to be able to use this library to intercept the stack trace before it is written to Seq and instead log the clean/modified stack trace.

Is there a way with Serilog/Seq to control the exact output of the error string that is sent to the log sink?


Solution

  • Perhaps enrichment might be helpful here. While not specifically discussed in that link, you can build custom enrichers:

    public class ExceptionEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            if (logEvent.Exception != null)
            {
                // do something here
    
                propertyFactory.CreateProperty("ExtraExceptionDetail", extraDetail);
            }
        }
    }
    

    then...

    var loggerConfig = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.Seq(url)
        .Enrich.With<ExceptionEnricher>()
        .Enrich.FromLogContext();
    

    I don't have any experience with the package you referenced, but this approach lets you intercept and modify/add/remove properties of the event before it's written to Seq.