Getting started with Log4net


This document provides how to use log4net. Its just an intro to getting started with log4net in a project for logging purpose. Follow the steps below :

1. Download log4net from the link http://logging.apache.org/log4net/download.html

2. Add reference of log4net.dll to the project  where to log, .

3.  In Web.config or App.config add following chunk of configuration :


<configSections> 
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 
</configSections>

<log4net> 
<appender name="rootRollingFile" type="log4net.Appender.RollingFileAppender,log4net"> 
<threshold value="ALL"/> 
<param name="File" value="E:\temp\Log.txt"/> 
<param name="AppendToFile" value="true"/> 
<param name="RollingStyle" value="Date"/> 
<param name="DatePattern" value=".yyyy.MM.dd.'log'"/> 
<param name="StaticLogFileName" value="false"/> 
<layout type="log4net.Layout.PatternLayout,log4net"> 
<param name="ConversionPattern" value="%date [%-5thread] %-5level %logger - %message%newline %exception"/> 
</layout> 
</appender> 
<root> 
<level value="ALL"/> 
<appender-ref ref="rootRollingFile"/> 
</root> 
</log4net>

remember to add the above configuration inside <configuration></configuration> tag. And change the File param value according to your choice.

4. At the start of your application call the following method :

 

log4net.Config.XmlConfigurator.Configure();

For web application the application starts from

protected void Application_Start(object sender, EventArgs e) {

log4net.Config.XmlConfigurator.Configure(); 
}
 

method in Global.asax.

For windows/console application application normally starts from the main method of program.cs, so place the code like :

[STAThread] 
static void Main() 
{ 
log4net.Config.XmlConfigurator.Configure(); 
Application.EnableVisualStyles(); 
Application.SetCompatibleTextRenderingDefault(false); 
Application.Run(new CheckNetStatus()); 
}

5. Its time to use log4net for logging.

6. Just use the following piece of code to log :

ILogger log = LoggerManager.GetLogger(this.GetType().Assembly, this.GetType());

log.Log(this.GetType(), Level.Info, "Error occured", null);

 

This is simply done!!!!!!!!!!!!

Advertisements