Click here to Skip to main content
11,412,516 members (69,500 online)
Click here to Skip to main content

How to use log4net

, 14 Jul 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes the basic steps to be followed for using Log4net in a web application.
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)

    Share

    About the Author

    Suman Kumar
    Web Developer
    India India
    No Biography provided

    Comments and Discussions

     
    QuestionProblem with Log4Net Pin
    Member 11021189 at 21-Apr-15 10:18
    memberMember 1102118921-Apr-15 10:18 
    AnswerRe: Problem with Log4Net Pin
    Member 11633193 at 22-Apr-15 5:00
    memberMember 1163319322-Apr-15 5:00 
    GeneralRe: Problem with Log4Net Pin
    Member 11021189 at 23-Apr-15 0:59
    memberMember 1102118923-Apr-15 0:59 
    GeneralMy vote of 3 Pin
    mahi0307 at 9-Oct-14 4:20
    membermahi03079-Oct-14 4:20 
    GeneralMy vote of 5 Pin
    harsha.bhuyan at 21-May-13 2:49
    memberharsha.bhuyan21-May-13 2:49 
    QuestionWhere is AssemblyInfo.cs Pin
    ariftk at 8-Jan-13 19:43
    memberariftk8-Jan-13 19:43 
    AnswerRe: Where is AssemblyInfo.cs Pin
    Avil Mascarenhas at 16-Oct-14 1:26
    memberAvil Mascarenhas16-Oct-14 1:26 
    GeneralMy vote of 5 Pin
    Kiran Kumar B at 10-Oct-12 21:20
    memberKiran Kumar B10-Oct-12 21:20 
    QuestionRead the configuration Pin
    Haitham.Hussien at 17-Sep-12 3:15
    memberHaitham.Hussien17-Sep-12 3:15 
    QuestionLog4Net Pin
    sivakarthiki at 9-Sep-12 7:14
    membersivakarthiki9-Sep-12 7:14 
    GeneralMy vote of 4 Pin
    Member 8599766 at 27-Aug-12 23:55
    memberMember 859976627-Aug-12 23:55 
    GeneralMy vote of 3 Pin
    yusia1 at 12-Jan-12 2:59
    memberyusia112-Jan-12 2:59 
    Questiongood article Pin
    ajaytiwari123456 at 30-Sep-11 2:16
    memberajaytiwari12345630-Sep-11 2:16 
    GeneralMy vote of 2 Pin
    jalalx at 24-Sep-11 1:36
    memberjalalx24-Sep-11 1:36 
    GeneralMy vote of 4 Pin
    Herminio Tribaldos at 27-Jul-11 22:13
    memberHerminio Tribaldos27-Jul-11 22:13 
    GeneralMy vote of 4 Pin
    RiteshPapneja at 20-Apr-11 23:03
    memberRiteshPapneja20-Apr-11 23:03 
    GeneralNot working while executing the exe(not in debug mode) Pin
    HaroldVish at 27-Jan-11 20:08
    memberHaroldVish27-Jan-11 20:08 
    GeneralMy vote of 3 Pin
    Pravin Patil, Mumbai at 17-Jan-11 21:53
    memberPravin Patil, Mumbai17-Jan-11 21:53 
    GeneralMy vote of 1 Pin
    zeltera at 14-Oct-10 5:59
    memberzeltera14-Oct-10 5:59 
    GeneralMy vote of 5 Pin
    pritam hinger at 16-Sep-10 0:40
    memberpritam hinger16-Sep-10 0:40 
    GeneralMy vote of 5 Pin
    zippy1981 at 14-Sep-10 5:11
    memberzippy198114-Sep-10 5:11 
    GeneralLog4net in Windows service Pin
    Jitendra Zaa at 7-Sep-10 22:08
    memberJitendra Zaa7-Sep-10 22:08 
    GeneralNot working Pin
    ravileeladhar at 22-Jul-10 0:40
    memberravileeladhar22-Jul-10 0:40 
    GeneralRe: Not working Pin
    Suman Kumar at 23-Jul-10 4:00
    memberSuman Kumar23-Jul-10 4:00 
    The log will be generated in the path declared in web.config file:

    <file value="C:\\TestLog4NetProj\\TestLog.log"/>

    Also the reason for log file not generated would be that the application is not finding the config file. You can try by adding below statement in code behind:

    log4net.Config.XmlConfigurator.Configure();

    GeneralFurther tutorials Pin
    Member 4109894 at 6-Apr-10 7:30
    memberMember 41098946-Apr-10 7:30 
    QuestionHow to read and parse the pattern entry from a log file? Pin
    nareshpatel at 17-Feb-10 22:18
    membernareshpatel17-Feb-10 22:18 
    AnswerRe: How to read and parse the pattern entry from a log file? Pin
    Suman Kumar at 18-Feb-10 8:43
    memberSuman Kumar18-Feb-10 8:43 
    GeneralRe: How to read and parse the pattern entry from a log file? Pin
    nareshpatel at 18-Feb-10 11:33
    membernareshpatel18-Feb-10 11:33 
    GeneralAnother good link for setting and implement log4net Pin
    MD.Tanvir Anowar at 15-Nov-09 17:18
    memberMD.Tanvir Anowar15-Nov-09 17:18 
    GeneralWeb.config slight change Pin
    Jack Choy at 11-May-09 10:21
    memberJack Choy11-May-09 10:21 
    Questionlog4NET Problem insert into MS SQL Server Pin
    What058 at 9-Mar-09 13:27
    memberWhat0589-Mar-09 13:27 
    QuestionHow to use log4net in vb.net class library? Pin
    Member 2213212 at 20-Jan-09 21:59
    memberMember 221321220-Jan-09 21:59 
    GeneralTurn logging on and off Pin
    Member 3853971 at 10-Oct-08 0:26
    memberMember 385397110-Oct-08 0:26 
    AnswerRe: Turn logging on and off Pin
    Suman Kumar at 18-Oct-08 19:09
    memberSuman Kumar18-Oct-08 19:09 
    GeneralThank you Pin
    Alain VIZZINI at 27-Jul-08 21:44
    memberAlain VIZZINI27-Jul-08 21:44 
    GeneralRe: Thank you Pin
    Suman Kumar at 14-Sep-08 19:27
    memberSuman Kumar14-Sep-08 19:27 
    GeneralSetting header and footer in a log Pin
    jason_X at 22-Jul-08 10:26
    memberjason_X22-Jul-08 10:26 
    Generallog4net and SharePoint Pin
    ld5221 at 9-Jan-08 8:46
    memberld52219-Jan-08 8:46 
    QuestionIt's not working in .net 2.0 Pin
    todeti at 23-Oct-07 7:11
    membertodeti23-Oct-07 7:11 
    AnswerRe: It's not working in .net 2.0 Pin
    Dadou002 at 21-Nov-07 9:04
    memberDadou00221-Nov-07 9:04 
    GeneralRe: It's not working in .net 2.0 Pin
    cse_king1 at 11-Apr-08 0:00
    membercse_king111-Apr-08 0:00 
    AnswerRe: It's not working in .net 2.0 Pin
    Jaroslav Martsek at 8-Jul-08 23:47
    memberJaroslav Martsek8-Jul-08 23:47 
    Questionlog4net config Pin
    Ravindra_sagar at 30-Sep-07 22:37
    memberRavindra_sagar30-Sep-07 22:37 
    GeneralError Pin
    Malayil alex at 23-Aug-07 4:17
    memberMalayil alex23-Aug-07 4:17 
    GeneralRe: Error Pin
    Suman Kumar at 5-Sep-07 19:17
    memberSuman Kumar5-Sep-07 19:17 
    GeneralHave you seen NLog? [modified] Pin
    Jaroslaw Kowalski at 17-Jul-06 5:28
    memberJaroslaw Kowalski17-Jul-06 5:28 
    GeneralRe: Have you seen NLog? Pin
    Suman Kumar at 20-Jul-06 20:24
    memberSuman Kumar20-Jul-06 20:24 
    Generallog4net sample Pin
    Rujith Anand at 16-Jul-06 22:34
    memberRujith Anand16-Jul-06 22:34 
    GeneralRe: log4net sample Pin
    Suman Kumar at 16-Jul-06 22:52
    memberSuman Kumar16-Jul-06 22:52 
    AnswerRe: log4net sample Pin
    Suman Kumar at 17-Jul-06 8:09
    memberSuman Kumar17-Jul-06 8:09 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

    | Advertise | Privacy | Terms of Use | Mobile
    Web04 | 2.8.150427.1 | Last Updated 14 Jul 2006
    Article Copyright 2006 by Suman Kumar
    Everything else Copyright © CodeProject, 1999-2015
    Layout: fixed | fluid