Reputation: 1073
Our legacy logging framework (.NET 4.5) would iterate over Exception.data and log each one of the Exception.data key values. It is nice for logging contextual props related to the current exception. Is there a way to configure Serilog to log the Exception.data key values?
Serilog 2
Upvotes: 5
Views: 1875
Reputation: 31832
This is the equivalent code for Serilog:
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);
}
}
You can find a complete program with configuration in this Gist.
A more sophisticated and flexible option is to use the Serilog.Exceptions package, which has smarts for a number of common exception types.
Upvotes: 8