Powered by Blogger.

Saturday, March 1, 2014

Log4Net in asp.net



In this post we will see how to use Log4Net in asp.net.

You can check my  previous posts on:

- Collections in C#.Net

- Constructor and Destructors in C#.Net

- Difference between primary key and unique key in SQL Server

Follow below steps in to use Log4Net in Asp.Net.

Step-1:
Dowonload log4net.dll from this web site.
http://logging.apache.org/log4net/index.html

After downloading give the reference in the Bin folder.

Step-2:
Then open the web.config file. Here we need to add two things:
- Add
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
inside the <configSections> tag.

- Then search for </system.web> and add the below code after this.

<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="c:\\AspDotNetHelp\MyLogs.log"/>
      <!-- Example using environment variables in params -->
      <!-- <param name="File" value="${TMP}\\ApplicationKit.log" /> -->
      <param name="AppendToFile" value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-2p %c [%x] - %m%n"/>
      </layout>
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>

Step-3:
Then open the global.asax file and add the below code in the Application_Start event.

log4net.Config.DOMConfigurator.Configure();


Step-4:
Now in this example we will log something in the page load. Below is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using log4net.Config;

public partial class _Default : System.Web.UI.Page
{
    ILog logger = log4net.LogManager.GetLogger(typeof(_Default).Name);
    protected void Page_Load(object sender, EventArgs e)
    {
        logger.Info("This is info message");

        logger.Debug("This is debug message");

        logger.Error("This is error message");

        logger.Warn("This is warn message");

        logger.Fatal("This is fatal message");
    }
}

Now if you open this c:\\AspDotNetHelp location then you will able to see the log.



0 comments

Post a Comment