Created
June 25, 2014 21:52
-
-
Save nblumhardt/dddaa2139bbf4b561fa7 to your computer and use it in GitHub Desktop.
Exception data enricher for Serilog
This file contains 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!"); | |
} | |
} | |
} |
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
this gist does NOT work at all. it doesn't provide any enrichment at all.