Logging with log4net

Written by John DeVight on 2011-May-11
Last Updated by John DeVight on 2011-May-18

rating: 0+x

Download RAZOR Source Code
Download ASPX Source Code

Overview

Apache log4net provides logging for .NET applications. It is a port of the log4j framework. Some of the key features of log4net are that it is easy to implement, supports multiple logging targets, allows for XML configuration and is thread safe.

The following implementation is based on log4net version 1.2.1.0.0.

Adding log4net to your Application

  1. Download log4net at: http://logging.apache.org/log4net/download.html
  2. In your .NET application, add a reference to the log4net.dll assembly. Note: each project in your solution that will use log4net will need to add a reference to the log4net.dll assembly.
  3. In your "start-up" project, whether that is an ASP.NET, Web Service, Windows Forms, Console or other type of application, you will need to add configuration information to a configuration file and load the configuration information when the application is started. This example focuses on a web based application.

Configuring log4net

In the Web.config file, add the following to "/configuration/configSections":

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

log4net can be setup to log to different destinations. Some of these destinations include relational databases, console, Visual Studio Debug window, email, local machine's application event log, file and more. Each destination is configured using an "appender". log4net can be configured to log to multiple appenders. The following shows how to log messages using a "RollingFileAppender" and "TraceAppender" (Visual Studio Debug window). In this example the "RollingFileAppender" will create a new file every day. Add the following to "/configuration":

<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:\Working_Folders\epxstudio-logfile.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%newline%newlineBEGIN LOG MESSAGE%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newlineEND LOG MESSAGE%newline%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="RollingLogFileAppender" />
    <appender-ref ref="TraceAppender" />
  </root>
</log4net>

When the "start-up" project runs, it will need to lead the log4net configuration information. In a web application, this is done in the Global.asax, Application_Start() event handler. Add the following code:

protected void Application_Start()
{
    log4net.Config.XmlConfigurator.Configure();
}

Each class will need to define a static log4net.ILog variable to perform logging. The following example shows the static variable being declared for the "HomeController" class.

public class HomeController : BaseController
{
    private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(HomeController));
}

Now you are ready to write log messages. It is a good practice (but not required) to check to see if the desired log level is enabled before attempting to write a log message. Each log level has a property that indicates whether the log level is enabled. Here is an example of checking to see if the INFO log level is enabled, and if so, log an INFO level log message:

public ActionResult NavigationTreeItems(TreeViewItem node)
{
    if (_logger.IsInfoEnabled) _logger.Info("NavigationTreeItems");

    // Some code here...
}

Here is an example of writing a FATAL level log message with an exception:

public ActionResult NavigationTreeItems(TreeViewItem node)
{
    try
    {
        // Some code here...
    }
    catch (Exception ex)
    {
        if (_logger.IsFatalEnabled) _logger.Fatal("NavigationTreeItems", ex);
    }
}

References

Support ASP.NET Wiki

If you like this page, click on the "Share on" links in the wikidot toolbar at the top of the page to share it with your friends.

Comments

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License