Click here to Skip to main content
6,306,412 members and growing! (17,903 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner License: The Code Project Open License (CPOL)

How to use log4net

By Suman Kumar

This article describes the basic steps to be followed for using Log4net in a web application.
C#, Windows, .NET, ASP.NET, Visual Studio, Dev
Posted:14 Jul 2006
Views:83,385
Bookmarked:64 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
30 votes for this article.
Popularity: 5.25 Rating: 3.55 out of 5
3 votes, 10.0%
1
2 votes, 6.7%
2
5 votes, 16.7%
3
5 votes, 16.7%
4
15 votes, 50.0%
5
Download source code - 103.9 Kb

Introduction

This article describes the basic steps to be followed for using Log4net in a web application. Log4net is an open source library that allows .NET applications to log statements to a variety of targets.

Background

This article assume you have basic working knowledge of C#, and ASP.NET programming.

Using the code

Log4net is very simple to use yet powerful logging option. This article describes log4net usage in a web application in six easy steps.

  • Step 1: Get the latest version of log4net library and add reference of it in your project.

  • Step 2: Add below line in your AssemblyInfo.cs file.
    [assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch=true)]   //For log4net 1.2.10.0
    Above statement provides the information about config file in which log4net configuration parameters are defined.

  • Step 3: Add below section in Web.Config file.
    <configSections>
    	<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    	
    <log4net debug="true">
    	<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    		<file value="C:\\TestProj\\TestLog.txt" />
    		<appendToFile value="true" />
    		<rollingStyle value="Size" />
    		<maxSizeRollBackups value="10" />
    		<maximumFileSize value="10MB" />
    		<staticLogFileName value="true" />
    		<layout type="log4net.Layout.PatternLayout">
    			<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
    		</layout>
    	</appender>
    	
    	<root>
    		<level value="DEBUG" />
    		<appender-ref ref="RollingLogFileAppender" />
    	</root>
    </log4net>
    

    Above section defines the configuration parameters to be used for logging.

    RollingLogFileAppender describes the appender to be used for logging. This means that the log should be written in a file, which will rollover when full. There are several other appender available and more than one appender can be attached to a logger.

    The layout is responsible for formatting the logging request, whereas an appender takes care of sending the formatted output to its destination. Layout used above would format the output as below:
    2006-07-14 20:26:04,033 [1736] ERROR Utility [PayStub] - Could not find a part of the path 
    "c:\inetpub\wwwroot\TestProj\Template\PayStub.xml"

  • Step 4: If you want log4net to add its own diagnostics messages then add below lines in web.config file.
    <appSettings>
        <add key="log4net.Internal.Debug" value="true" />
    </appSettings>
    Add below lines after system.web section:
    <system.diagnostics>
        <trace autoflush="true">
            <listeners>
                <add name="textWriterTraceListener" 
                   type="System.Diagnostics.TextWriterTraceListener" 
                   initializeData="C:\\TestProj\\TestProjlog4net.txt" />
            </listeners>
        </trace>
    </system.diagnostics>

  • Step 5: Now follow below steps in your code-behind.

    a. Add namespace

    using log4net;

    b. Add below declarations within class definition

    private static readonly ILog log = LogManager.GetLogger(typeof(TestPage1).Name);
    OR
    private static readonly ILog log = LogManager.GetLogger(
      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  • Step 6: Now you are ready for logging. Use below statements to log your messages in log file:
    if (log.IsErrorEnabled)
    {
        log.Error("Page Load failed : " + ex.Message);
    }
    OR
    if (log.IsDebugEnabled)
    {
        log.Debug("Application loaded successfully.");
    }
    We have just scratched the surface of log4net. There are several other good features available in log4net and it can be used to collect vital information for several purposes. Happy Programming.

    History

    • 07/14/2006 - Article submitted.
    • 07/19/2006 - Added Sample Project & updated the article.
  • License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    Suman Kumar


    Member

    Occupation: Web Developer
    Location: India India

    Other popular ASP.NET articles:

    Article Top
    You must Sign In to use this message board.
    FAQ FAQ 
     
    Noise Tolerance  Layout  Per page   
     Msgs 1 to 22 of 22 (Total in Forum: 22) (Refresh)FirstPrevNext
    GeneralWeb.config slight change PinmemberJack Choy10:21 11 May '09  
    Questionlog4NET Problem insert into MS SQL Server PinmemberWhat05813:27 9 Mar '09  
    GeneralHow to use log4net in vb.net class library? PinmemberMember 221321221:59 20 Jan '09  
    GeneralTurn logging on and off PinmemberMember 38539710:26 10 Oct '08  
    AnswerRe: Turn logging on and off PinmemberSuman Kumar19:09 18 Oct '08  
    GeneralThank you PinmemberAlain VIZZINI21:44 27 Jul '08  
    GeneralRe: Thank you PinmemberSuman Kumar19:27 14 Sep '08  
    GeneralSetting header and footer in a log Pinmemberjason_X10:26 22 Jul '08  
    Generallog4net and SharePoint Pinmemberld52218:46 9 Jan '08  
    QuestionIt's not working in .net 2.0 Pinmembertodeti7:11 23 Oct '07  
    AnswerRe: It's not working in .net 2.0 PinmemberDadou0029:04 21 Nov '07  
    GeneralRe: It's not working in .net 2.0 Pinmembercse_king10:00 11 Apr '08  
    AnswerRe: It's not working in .net 2.0 PinmemberJaroslav Martsek23:47 8 Jul '08  
    Questionlog4net config PinmemberRavindra_sagar22:37 30 Sep '07  
    GeneralError PinmemberMalayil alex4:17 23 Aug '07  
    GeneralRe: Error PinmemberSuman Kumar19:17 5 Sep '07  
    GeneralHave you seen NLog? [modified] PinmemberJaroslaw Kowalski5:28 17 Jul '06  
    GeneralRe: Have you seen NLog? PinmemberSuman Kumar20:24 20 Jul '06  
    Generallog4net sample PinmemberRujith Anand22:34 16 Jul '06  
    GeneralRe: log4net sample PinmemberSuman Kumar22:52 16 Jul '06  
    AnswerRe: log4net sample PinmemberSuman Kumar8:09 17 Jul '06  
    GeneralWTF Pinmembermango_lier22:25 15 Jul '06  

    General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    PermaLink | Privacy | Terms of Use
    Last Updated: 14 Jul 2006
    Editor:
    Copyright 2006 by Suman Kumar
    Everything else Copyright © CodeProject, 1999-2009
    Web11 | Advertise on the Code Project