Last active
December 16, 2015 04:39
-
-
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
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 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; | |
} | |
} | |
} |
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
<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