Skip to content

Instantly share code, notes, and snippets.

@mika76
Forked from nblumhardt/Program.cs
Created February 27, 2019 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mika76/f976624d41b202cfe909c3a44e4dfb86 to your computer and use it in GitHub Desktop.
Save mika76/f976624d41b202cfe909c3a44e4dfb86 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!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment