Thursday, July 31, 2014

log4net: EventLogAppender

Using the EventLogAppender in log4net allows you to post messages to the Windows Event Log so that they can be seen in the Event Viewer.  However, there are a few “special” issues with this logger that I’d like to point out.

Here’s a typical appender definition:

<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="MainService" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>

<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>


1) applicationName attribute
The application name is what the “source” column will display in the event viewer:
image 
2) Default Event ID is 0 – Causes error message
image If you do not specify an EventID, then by default, the EventID logged with the message is 0.  This causes the event viewer to display a warning with you message content (1):
The description for Event ID 0 from source MainService cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event:


You message is still displayed (2), but you will have this message displayed first.

To eliminate this message, you simply need to specify an EventID greater than 0 in either the ThreadContext or GlobalContext arrays for log4net.  I will let you research this further on your own, but to quickly get rid of the message, right after you configure log4net in your application, just set the GlobalContext property like this:

XmlConfigurator.ConfigureAndWatch(new FileInfo(@".\log4net.config"));
GlobalContext.Properties["EventID"] = 1;
var log = LogManager.GetLogger(typeof(Program));

With a 1 as the EventID, your logged message will be cleaner:
image


3) log4net Levels and Event Log Levels
When logging log4net messages in the Event Log, here is how the “levels” translate:

log4net Level –> Windows Event Log Level
DEBUG, INFO –> Information
WARN –> Warning
ERROR, FATAL –> Error

image

No comments:

Post a Comment