How to use Log4Net

Hi , in today’s post , i am going to explaing a sample , to use log4net assembly , which is used for Logging and faster than Enterprise library.

follow the steps :

(1)Create a new web site project in VS200*.

(2)Add reffernce to the Log4net assembly to your website and add using log4net namespace.

(3) add a confguration file and name it myLogConfig.config.

(4)Add the  the following content to this file

<?xml version=”1.0″ encoding=”utf-8″ ?>
<log4net>
<root>
<level value=”DEBUG” />
<appender-ref ref=”RollingLogFileAppender”/>
</root>
<appender name=”RollingFileAppender” type=”log4net.Appender.RollingFileAppender”>
<file value=”app.log” />
<appendToFile value=”true” />
<rollingStyle value=”Size” />
<maxSizeRollBackups value=”10″ />
<maximumFileSize value=”100KB” />
<staticLogFileName value=”true” />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%d [%t]%-5p %c [%x] – %m%n” />
</layout>
</appender>
<appender name=”RollingLogFileAppender” type=”log4net.Appender.RollingFileAppender”>
<file value=”app.log” />
<appendToFile value=”true” />
<datePattern value=”-dddd” />
<rollingStyle value=”Date” />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%d [%t]%-5p %c [%x] – %m%n” />
</layout>
</appender>
</log4net>

(5)Add global.ascx to  your website and add the following method

protected void ConfigureLogging()
{
string logFile = HttpContext.Current.Request.PhysicalApplicationPath + “log4net.config”;
if (System.IO.File.Exists(logFile))
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(logFile));
}
}

 

(6)Call this method

void Application_Start(object sender, EventArgs e)
{
ConfigureLogging();

}

 

 

 

  (7) Now in your default.aspx.cs file add the following  code

log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
log.Debug(“In Page Load Function”);
log.Debug(“Going to generate divide by zero”);
int a = 0;
int b = 10 / a;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}

 

Now run your application and have alook at the newly created log file .

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