Saturday, December 7, 2013

log4net.Appender.EventLogAppender and WCF

So I finally cracked the magic behind getting the log4net EventLogAppender to work within a WCF service and very likely any other web related solution.  Initially after pulling my hair out and spending hours pouring over StackedOverflow and log4net postings had I given up any hope of finding a way to get this working.  Most of the solutions offered either sounded scary - for instance like adding the identity of the application pool within the Administrators group on the local machine!?!  Or simply didn't work like the instructions in the documentation over at Apache -which left out crucial step if you are writing WCF or other web projects.  Hopefully if you come across this it might shed some light on the subject, prevent hours of frustration, and get you working.

The documentation over at Apache isn't complete when it comes to setting up log4net to use the Windows event viewer.  While the settings illustrated are precisely correct they leave out a two key ingredients - things which must be done to get this to work.

First there is some meaning behind the log4net proper within the EventLogAppender property called "ApplicationName" which should be set within your web.config.  An example of the confing file can found over at Apache's config examples under the EventLogAppender settings.  However, here is the property that I am specifically speaking about:

<applicationName value="YourAppName" />

This application name actually defines the value that will appear in the "Source" column in the event viewer.

Second, in order to actually write out to the event viewer you need to do some registry work.  Navigate to the following area of your registry (or if you are wanting to write to another section of the event viewer navigate to that):

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application

Within this section (assuming you want the event log's to appear under the Windows Logs/Application section) add a new key that is EXACTLY the same as the ApplicationName defined in above.  Within this key add a new string element called "EventMessageFile" and set the value to:


%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll

Once this is done reset the application pool and you should start seeing the Application event log entries with the "source" equal to the name of the ApplicationName set in your log4net <appender> group.

In order to avoid having to do all this typing on each of the target servers I'd recommend that you extract the key you added and place that in your project for safe keeping.  This registry file can then be imported into the registry of the target server(s) you are deploying your application.  Adding to the project and eventually to version control will help keep your work around and handy for others.