Skip to content

Instantly share code, notes, and snippets.

@Scooletz
Last active December 16, 2015 04:39
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 Scooletz/5378807 to your computer and use it in GitHub Desktop.
Save Scooletz/5378807 to your computer and use it in GitHub Desktop.
log4net enhancement for adding exception into to log4net, especially EventLog based appender. View http://blog.scooletz.com/2013/04/15/enhancing-log4net-exception-logging for more information
using System;
using log4net.Core;
using log4net.Filter;
using log4net.Util;
namespace Log4NetEnhancing
{
public class ExceptionBasedLogEnhancer : FilterSkeleton
{
private const string EventLogKeyEventId = "EventID";
private const string EventLogKeyCategory = "Category";
public override FilterDecision Decide(LoggingEvent loggingEvent)
{
var ex = loggingEvent.ExceptionObject;
if (ex != null)
{
EnhanceWithException(loggingEvent.Properties, ex);
}
return FilterDecision.Neutral;
}
private static void EnhanceWithException(PropertiesDictionary properties, Exception ex)
{
if (ex.Source != null)
{
properties["ExceptionSource"] = ex.Source;
// for event logs
properties[EventLogKeyEventId] = GetEventId(ex);
properties[EventLogKeyCategory] = GetCategory(ex);
}
}
private static int GetEventId(Exception ex)
{
// more fancy implementation, like getting hash of ex properties can be provided, or mapping types of exceptions to eventids
// return no more than short.MaxValue, otherwise the EventLog will throw
return 0;
}
private static short GetCategory(Exception ex)
{
// more fancy implementation, like getting hash of ex properties can be provided, or mapping types of exceptions to category
return 0;
}
}
}
<appender name="MyEventLogAppender" type="log4net.Appender.EventLogAppender">
<filter type="Log4NetEnhancing.ExceptionBasedLogEnhancer, Log4NetEnhancing"></filter>
</appender>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment