Friday, January 2, 2009

Log4Net with ASP.NET Application

I implemented log4net before but as usual, I could not remember all the steps to do it again in my UTS web application !! I also remember one of my team members (the same who deleted oracle directory under linux :P ) who had difficulties implementing for some weird reason which even i could not figure out. So, here i go documenting the simplest implementation of log4net in an ASP.NET Web application.

(1) First of all Download log4net extension

(2) Create a seperate log4net.config file and place all your configurations. Mine are as follows:

<?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="../logs/utslog.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="../logs/utslog.log" />
    <appendToFile value="false" />
    <datePattern value="-dddd" />
    <rollingStyle value="Date" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d [%t]%-5p %c [%x] - %m%n" />
    </layout>
  </appender>
</log4net>

(3) In your Global.asx, add the following method that will instantiate log4net configuration for your web app. Make a call to this method in Application_Start

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));
    }
}

(4) To use log4Net in your code behind simply initialize an instance of log4net

#region Logger Setup
    protected static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion

 

(5) To eventually use logging in your code behind

protected void Page_Load(object sender, EventArgs e)
{

      log.Debug("In Page Load Function"); 

}

 

No comments: