Friday, December 23, 2011

How to write log using log4net in asp.net.

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime.
This article describes the easy way to be followed for using File Appender of Log4net to write to a text file in a web application day by day.

First of all, get the latest version of log4net library and add reference of it in your project. You can download here : http://logging.apache.org/log4net/download_log4net.cgi.

Add below line in your AssemblyInfo.cs file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch=true)]

Folder where you put log4net











Add below section in Web.Config file.

<configuration>
  <configSections>
    <!-- log4net START here-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    <!-- log4net STOP here-->
  </configSections>
  <!-- log4net START here-->
  <log4net>
    <root>
      <level value="ALL"/>
      <appender-ref ref="MyTxt"/>
    </root>
    <appender name="MyTxt" type="log4net.Appender.RollingFileAppender">
      <file value="G:\Log_"/>
      <!-- This is file path to save the log. Note : don't put file extension.-->
      <appendToFile value="true"/>
      <datePattern value="yyyy-MM-dd.\tx\t"/>
      <!-- This is date format for file name to save the log.-->
      <rollingStyle value="Date"/>
      <param name="StaticLogFileName" value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%-5thread] %-5level : %logger : %message %timestampms %n"/>
      </layout>
    </appender>
  </log4net>
  <!-- log4net END here-->
  <appSettings>
    <add key="logging" value="Y"/>
    <!-- Here is boolean flag to log or not-->
  </appSettings>
  //Other sections may go here
</configuration>

Add one class Logging.cs file.
public class Logging
{
    public Logging()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public static void logMsg(string msg, ref log4net.ILog log)
    {
         if (ConfigurationManager.AppSettings["logging"].ToString().Equals("Y"))
        {
            //There are seven logging levels.
            log.Error("MyApp : " + msg);
            //log.Fatal("MyApp : " + msg);
            //log.Warn("MyApp : " + msg);
            //log.Info("MyApp : " + msg);
            //log.Debug("MyApp : " + msg);
        }
    }
}

In your code-behind,
//declare private static variable.
private static log4net.ILog log4 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        String Qs = Request.QueryString["id"].ToString();
        //here cause error when it miss id querystring.
    }
    catch (Exception ex)
    {
        Logging.logMsg(ex.Message, ref log4);
    }
}

when it lead to error every times, it save the error in log file(here may be Log_2011-12-22.txt) and log statement may be similar as below :
2011-12-22 16:37:47,034 [4688 ] ERROR : WebAppBlog._Default : MyApp : Object reference not set to an instance of an object. 534ms

That's it. Thank for reading.

No comments:

Post a Comment