Log4Net is a logging tool for .NET.

In this article I will be showing the basic steps of configuring log4Net in your web application.

Following are the steps to implement log4net in your applications:

Step 1 :

In the web.config file add the following xml node :

[sourcecode language="csharp"]
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="TestLog.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="yyyyMMdd"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c:%L] - %m%n"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
[/sourcecode]

"<file value="TestLog.txt"/>"  specifies the name of the file where the errors/warnings will be logged.

Step 2 :

Add the reference of the log4net to the project.I have attached the log4net .dll hereby.

Download the file from here and rename it as log4net.dll.

Step 3:

In the global.asax file add the following namespaces

[sourcecode language="csharp"]
using log4net;
using log4net.Config;
using log4net.Repository;
using log4net.Repository.Hierarchy;
[/sourcecode]

In the Application_Start Method of Global.asax.cs page add the below code:

[sourcecode language="csharp"]
protected void Application_Start(object sender, EventArgs e)
{
XmlConfigurator.Configure();
}
[/sourcecode]

Step 4:

Now add the following code to whichever page you want to log the exception using log4net:

[sourcecode language="csharp"]
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
[/sourcecode]

Step 5:

Now in the catch() section of the method you can add the following line of code:

[sourcecode language="csharp"]
logger.Error(ex.Message);
[/sourcecode]

There are different logging levels, which can be called in the code. They are as follows:

  • OFF
  • FATAL
  • ERROR
  • WARN
  • INFO
  • DEBUG
  • ALL

This is how you can successfully configure log4Net in your web application.

# Note:

In order to put OFF the log4net functionality, you can just add the following line to the web.config:

[sourcecode language="csharp"]
<log4net></pre>
<log4net threshold="OFF" />
<appender>.....
[/sourcecode]

[/sourcecode]Let me know if you face any further issue on this.