Code -> Break -> Fix -> Blog

Logging to Windows Event Log using Log4Net Utility

Leave a comment

1. Install log4net NUGET package.


2. Edit AssemblyInfo.cs

Add the below line in the AssemblyInfo.cs:

[assembly : log4net.Config.XmlConfigurator(Watch=true)]

3. Edit App.config

Add the below <configSections> as the 1st element under <configuration>

 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />

Add the below <log4net> section in app.config

 <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
 <param name="LogName" value="LogginSampleLog" />
 <param name="ApplicationName" value="LoggingSample" />
 <layout type="log4net.Layout.PatternLayout">
 <conversionPattern value="{%level} {%date} – %message%newline" />
 <level value="DEBUG" />
 <appender-ref ref="EventLogAppender" />

4. Add a LogUtility class

static class LoggerUtility
private static ILog logger;

public static ILog Logger
return logger;

public static void InitializeLogger()
if (log4net.LogManager.GetCurrentLoggers().Length == 0)
logger = log4net.LogManager.GetLogger(&quot;EventLogAppender&quot;); // OR logger = log4net.LogManager.GetLogger(typeof(LoggerUtility));
logger.Info(&quot;Begin processing.&quot;);

5. Update registry (Create event source)

As mentioned in here, there are two ways to do this.

  • Update the Windows registry directly
  • Create an Installer using EventLogInstaller class.

6. Lets try it out

class Program

static void Main(string[] args)
LoggerUtility.Logger.Info("Application started.");

string strName = null;

Console.WriteLine("Name : " + strName.ToString());
catch (NullReferenceException nullException)
LoggerUtility.Logger.Error("Name is NULL", nullException);

LoggerUtility.Logger.Info("Application ended.");


After you run the above application, you can see the below output in EventViewer.


Hope this helps.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s