Using Log4Net in your application


Using Log4Net for logging errors

Step 1:Download and install Log4Net from http://logging.apache.org/log4net/download.html

Step 2: Right click the project and add a reference to log4net.dll by selecting browse tab.

Step 3: Add the Log4Net configuration information to your web.config file.


<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net-net-1.0"/>
</configSections>

<log4net>
<appender name="TraceAppender" type="log4net.Appender.RollingFileAppender">
<file value="Application.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<countDirection value="1" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.XmlLayout" />
</appender>
<logger name="LoggingExample">
<level value="ALL" />
<appender-ref ref="TraceAppender" />
</logger>
</log4net>

Step 2:

Add the following code in your application to load the configuration for Log4Net.

string logFile = HttpContext.Current.Request.PhysicalApplicationPath + "web.config";
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(logFile));


Step 3:

Create a log category before logging any message by using LogManager class

public static log4net.ILog logger = log4net.LogManager.GetLogger("LoggingExample");

Step 4:

Log the message or exceptions in application as below.

try {

logger.Info("You are in try block");

}

catch(Exception ex)
{

logger.Error("Error in application: ", ex);

}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: