LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Using Apache's log4net in ASP.NET
by Anubhav(Ash) Srivastava
Average Rating: 
Views (Total / Last 10 Days): 42198/ 110


[Download Code]

Log4net is a .NET component from Apache Foundation that provides a simple mechanism for logging messages. Log4net provides seven levels of logging, which are listed below from lowest to highest priority:

1. ALL
7. OFF

These levels help control the output to log files. If in the configuration file the level for a class is set to ERROR, then all messages from that class at a level below ERROR (i.e., DEBUG, INFO or WARN) will not be logged. This will come in very handy when the application goes into production. If you find yourself a little confused, do not worry. Let's proceed with a sample application and you will soon be a log4net pro.

Creating the Sample Application

[Download Code]

Step 1: Download log4net

Visit and select “download at” from the navigation menu. You will see the SourceForge page as shown in Figure 1. Download the file named 1.2.0 Beta8 ( and unzip this archive to your C:\ directory.

Figure 1

Step 2: Create a new ASP.NET Application

Start Visual Studio .NET and create a new Web Application project named LogHelloWorld, as shown in Figure 2.

Figure 2

Click OK. In the Solution Explorer window, right-click on References and select Add a Reference. Select Browse and navigate to C:\log4net-1.2.0-beta8\bin\net. There, select the subfolder matching the version of .NET you are using. Inside its \release subfolder, select the log4net.dll file.

Figure 3

After you have selected the file, click OK, and you will see that the log4net assembly has been added as a reference.

Configuring the Sample Application

[Download Code]

Step 3: Add Assembly Information

Open the AssemblyInfo.cs file and add the following line:

[assembly: log4net.Config.DOMConfigurator()]

The above line is needed because the log4net configuration can be configured using assembly-level attributes rather than specified programmatically. If you are using your own configuration file rather than Web.config then you will have to specify it here along with its extension. You also have the option to set the Watch flag to true, which will make log4net reload the config each time the file is modified. So it will look like the following.

[assembly: log4net.Config.DOMConfigurator(ConfigFile="filename",ConfigFileExtension="log4net",Watch=true)]

Step 4: Add Configuration Information

Open the Web.config file and add the following code within its configuration tags. It is important that the configSections node is placed immediately after the opening configuration tag, as shown below.

<?xml version="1.0" encoding="utf-8" ?>
    <section name="log4net" 
             type="log4net.Config.Log4NetConfigurationSectionHandler, log4net-net-1.0" 

  <!-- This section contains the log4net configuration settings -->
    <!-- Define some output appenders -->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
    <!-- RollingFileAppender looks after rolling over files by size or date -->
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="C:\\log\\RollingLogHelloWorld.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="10" />
      <param name="MaximumFileSize" value="1000" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %-45c [%x] - %m%n" />
    <!-- FileAppender appends to a log and it is manually managed or size -->
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="LogHelloWorld.log" />      
      <!-- Example using environment variables in params -->
      <!-- <param name="File" value="${TMP}\\ApplicationKit.log" /> -->
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
    <!-- Setup the root category, add the appenders and set the default level -->
      <level value="INFO" />
      <appender-ref ref="ConsoleAppender" />
    <!-- ApplicationKit category - the presentation UI -->
    <logger name="WebForm1">
      <level value="INFO" />
      <appender-ref ref="FileAppender" />

Towards the end of the configuration file above, please note the logger node with its name attribute set to WebForm1. This identifies the name of our class. For every class in which you want to use logging, you must add an additional logger node to the log4net section of the Web.config file.

In the logger node above, the level is set to INFO, so all messages that are of lower priority than INFO will not be logged for this WebForm1 class.

Running the Sample Application

[Download Code]

Step 5: Add a Log Object 

Add the following directives to the top of the WebForm1.aspx.cs code-behind file.

using log4net;
using log4net.Config;

Add the following line in the WebForm1 class; its placement is shown in Figure 4 below.

private static readonly ILog log = LogManager.GetLogger("WebForm1");

Figure 4

Step 6: Use the Log Object

Our application is now ready to log messages from the WebForm1 class. To test this, drag a Button control from the toolbox onto WebForm1.

Figure 5

Double-click the Button and add the following code to the Button1_Click event handler.

log.Info("Hello World, I am a logger");

Step 7: Run the Application

We are now ready to test our application and its logging component. To launch the application, press F5. A web page similar to the following should appear in your browser:

Figure 6

Click on the button to trigger a postback, during which log4net will record our message. Using Notepad, open the file named LogHelloWorld.log in the application's \bin\Debug directory. All going well, you will see a log similar to that shown below.

Figure 7


I hope that this article has demonstrated how easy it is to add the log4net component to your ASP.NET application. For more information, please visit Apache's log4net homepage:


©Copyright 1998-2021  |  Page Processed at 2021-07-26 11:32:51 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search