Tuesday, April 12, 2011

How to use Log4Net in asp.net?

Log4Net is used to log messages into a file in system drive as well as it will send Email. There are 5 levels of Logging like

You can download the library from this URL http://logging.apache.org/log4net/index.html

Step-1: After downloading click Add Reference project and refer to the log4net.dll
Step-2: Changes in the web.config file. Make below 2 entries in the web.config file.

Put the below code after <configSections>

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

And put the below code after </system.web>










Step-3: Changes in the global.asax

Put log4net.Config.DOMConfigurator.Configure(); inside Application_Start like below

void Application_Start(object sender, EventArgs e)


// Code that runs on application startup



Now go to the file where you want to trap information, In my case Default.aspx.cs

Import below 2 namespaces.

using log4net;

using log4net.Config;

Write ILog logger = log4net.LogManager.GetLogger(typeof(_Default)); inside the class declaration, above page_load.

Now you can trap the errors by

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

After this open the path provided in the web.config. In my case c:\xxx\Log4NetExample.log file will be found with the trapped information.

1 comment: