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 :
<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>
“<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
using log4net; using log4net.Config; using log4net.Repository; using log4net.Repository.Hierarchy;
In the Application_Start Method of Global.asax.cs page add the below code:
protected void Application_Start(object sender, EventArgs e) { XmlConfigurator.Configure(); }
Step 4:
Now add the following code to whichever page you want to log the exception using log4net:
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Step 5:
Now in the catch() section of the method you can add the following line of code:
logger.Error(ex.Message);
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:
<log4net></pre> <log4net threshold="OFF" /> <appender>.....
[/sourcecode]Let me know if you face any further issue on this.