-
-
Save mika76/f976624d41b202cfe909c3a44e4dfb86 to your computer and use it in GitHub Desktop.
Exception data enricher for Serilog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Serilog; | |
using Serilog.Core; | |
using Serilog.Events; | |
using Serilog.Formatting.Json; | |
using Serilog.Sinks.IOFile; | |
namespace ExceptionDataEnrichment | |
{ | |
public class ExceptionDataEnricher : ILogEventEnricher | |
{ | |
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) | |
{ | |
if (logEvent.Exception == null || | |
logEvent.Exception.Data == null || | |
logEvent.Exception.Data.Count == 0) return; | |
var dataDictionary = logEvent.Exception.Data | |
.Cast<DictionaryEntry>() | |
.Where(e => e.Key is string) | |
.ToDictionary(e => (string)e.Key, e => e.Value); | |
var property = propertyFactory.CreateProperty("ExceptionData", dataDictionary, destructureObjects: true); | |
logEvent.AddPropertyIfAbsent(property); | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var log = new LoggerConfiguration() | |
.Enrich.With<ExceptionDataEnricher>() | |
.WriteTo.Sink(new FileSink("log.jsnl", new JsonFormatter(), null)) | |
.CreateLogger(); | |
try | |
{ | |
var thrown = new InvalidOperationException("This is an error"); | |
thrown.Data["ExtraInfo"] = 123; | |
throw thrown; | |
} | |
catch (Exception caught) | |
{ | |
log.Error(caught, "Here's an error"); | |
} | |
Console.WriteLine("Done!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment