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″ ?>
<level value=”DEBUG” />
<appender-ref ref=”RollingLogFileAppender”/>
<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” />
<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” />

(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)





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

log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
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 .


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