Bhavya

Code -> Break -> Fix -> Blog

Logging to Windows Event Log using Log4Net Utility

Leave a comment

1. Install log4net NUGET package.

Nuget

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>


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

Add the below <log4net> section in app.config

 <log4net>
 <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" />
 </layout>
 </appender>
 <root>
 <level value="DEBUG" />
 <appender-ref ref="EventLogAppender" />
 </root>
 </log4net>

4. Add a LogUtility class


static class LoggerUtility
{
private static ILog logger;

public static ILog Logger
{
get
{
return logger;
}
}

public static void InitializeLogger()
{
if (log4net.LogManager.GetCurrentLoggers().Length == 0)
{
log4net.Config.BasicConfigurator.Configure();
}
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.InitializeLogger();
LoggerUtility.Logger.Info("Application started.");

string strName = null;

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

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

Output:

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

Error

Hope this helps.

~BS

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s