Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
Joe Camp Avatar asked Sep 16 '16 21:09

Joe Camp


1 Answers

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.

like image 135
Rob Davis Avatar answered Sep 23 '22 10:09

Rob Davis