Skip to content

Instantly share code, notes, and snippets.

@nblumhardt
Created June 25, 2014 21:52
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nblumhardt/dddaa2139bbf4b561fa7 to your computer and use it in GitHub Desktop.
Save nblumhardt/dddaa2139bbf4b561fa7 to your computer and use it in GitHub Desktop.
Exception data enricher for Serilog
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!");
}
}
}
@nblumhardt
Copy link
Author

Works perfectly for me; could be an issue elsewhere in your setup?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment