Click here to Skip to main content
Email Password   helpLost your password?
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

  • You must Sign In to use this message board.
     
     
    Per page   
     FirstPrevNext
    GeneralHow to read and parse the pattern entry from a log file?
    nareshpatel
    22:18 17 Feb '10  
    Guys,

    I want to read the entry from log file and parse it to get the required details.

    Regards,
    AnswerRe: How to read and parse the pattern entry from a log file?
    Suman Kumar
    8:43 18 Feb '10  
    You can write a small parser to parse & display the file content in a suitable interface (maybe ASP.NET web app etc.)
    GeneralRe: How to read and parse the pattern entry from a log file?
    nareshpatel
    11:33 18 Feb '10  
    Yes but how do i split up the log entry and categorize the fields? And what if there are some additional patterns like header and footers?

    I know how to read a file but only concern is splitting the entry and categorize the fields.

    Any code snippet will help a lot?

    Regards,
    Nash
    GeneralAnother good link for setting and implement log4net
    MD.Tanvir Anowar
    17:18 15 Nov '09  
    Hello

    In the the following blog there is very good comprehensive article of log4net setup.

    http://blog.actcode.com/2009/11/net-application-logging-with-log4net-in.html
    Thanks
    GeneralWeb.config slight change
    Jack Choy
    10:21 11 May '09  
    I'm using log4net 1.2.10 and wanted to let you know that I could not get logging to work correctly until I wrapped the sample Web.config file with <configuration> and </configuration>
    Questionlog4NET Problem insert into MS SQL Server
    What058
    13:27 9 Mar '09  
    I use log4NET in my web app and all was working correctly .. i used log4net to write a log into a table in my database in MS SQL Server 2005 , but about 4 days ago the log4net stop to do it , when I trace the transactions in the database I found this:

    The log4net change my insert query to this :
    exec sp_execute 1 (values) and the log was working fine , but suddenly change to this:
    exec sp_execute -1 (values) and stop the write.

    My question is : why the log4net would change : exec sp_execute 1 to exec sp_execute -1

    .. hope someone understand my problem ...

    thanks


    -S.
    GeneralHow to use log4net in vb.net class library?
    Member 2213212
    21:59 20 Jan '09  
    Log4Net is giving proper logs when i use with Exe`s. But not with Class Libraries. I followed same steps in both exe and library. But its not writing logs in case of dll.

    I followed following steps...
    1. Added log4net.dll in references
    2. In assemblyInfo.vb file added (<Assembly: log4net.Config.XmlConfigurator()> )
    3. In class file declared (Private Shared ReadOnly log As ILog = LogManager.GetLogger("Log4NetLib"))
    4. Added app.config file
    5. In function i added logs like (log.Debug("..........."))

    Works fine for exe but not dll.

    Am i doing anything wrong? can you please advice me?

    Thanks in advance
    -Surya

    Surya

    GeneralTurn logging on and off
    Member 3853971
    0:26 10 Oct '08  
    Hi Do we have any property in Log4Net so that we can set in the configuration file and turn it off for the time being.

    gfhgf

    AnswerRe: Turn logging on and off
    Suman Kumar
    19:09 18 Oct '08  
    You can achieve it by setting "threshold" attribute to "OFF"

    For example:
    <log4net threshold="OFF" debug="true">
    GeneralThank you
    Alain VIZZINI
    21:44 27 Jul '08  
    Thanks for writing this page, it was very helpful.
    Log4net samples are so poorely documented, that starting logging can take up to hoursConfused . Getting it to work is definately the worst (and maybe only?) problem of log4net.
    Anyway, once again thanks a lot!

    Alain.
    GeneralRe: Thank you
    Suman Kumar
    19:27 14 Sep '08  
    Thanks.
    GeneralSetting header and footer in a log
    jason_X
    10:26 22 Jul '08  
    Hi,

    how can I customize the header and footer? I wanna have the following information in the header:
    - "program start: " + System.DateTime.Now().ToString
    - "computer: " + System.Environment.MachineName()
    - "User: " + System.Environment.UserDomainName + "\" + System.Environment.UserName
    - "application: " + System.Diagnostics.Process.GetCurrentProcess.ProcessName

    In the footer I wanna write:
    - "_______________________________________________________________________"
    - "program end: " + System.DateTime.Now().ToString
    - "execution time: " + blabla

    Is this possible?

    And I got another question: Can I set another location of the config.xml instead of the application directory?

    thx in advance!

    jason_x
    Generallog4net and SharePoint
    ld5221
    8:46 9 Jan '08  
    Do you have any suggestions as to how to use log4net and SP 2007 webparts? Do I still put the configuration settings in web.config event though all webparts use the same web.config? Thanks.
    QuestionIt's not working in .net 2.0
    todeti
    7:11 23 Oct '07  
    It's not working in .net 2.0
    AnswerRe: It's not working in .net 2.0
    Dadou002
    9:04 21 Nov '07  
    Yes it is, just download the latest log4net dll
    GeneralRe: It's not working in .net 2.0
    cse_king1
    0:00 11 Apr '08  
    Its not working still... Everything builds fine... but while running, its not writting to any file...
    AnswerRe: It's not working in .net 2.0
    Jaroslav Martsek
    23:47 8 Jul '08  
    Please make sure that log4net is initialized - check the article for details.

    Also if you specify in your config section log4net with attribute debug="true" and start the application in debugger on your output window you will see the potential error messages.

    If you don't see any - you have not log4net properly initilaized - check the article for details.

    Hope this helps.
    Questionlog4net config
    Ravindra_sagar
    22:37 30 Sep '07  
    Sir,
    I have an asp.net application that uses log4net for logging purpose. And i want to integrate my application with the other asp.net application i.e. host application. the problem comes here i want to log both application in two different log files.
    (This is a integrated environment)
    How can i solve this , plz help me out.

    Thanks in advance
    Ravindra
    GeneralError
    Malayil alex
    4:17 23 Aug '07  
    It's not working in my side...
    GeneralRe: Error
    Suman Kumar
    19:17 5 Sep '07  
    Can you provide the error description.
    GeneralHave you seen NLog? [modified]
    Jaroslaw Kowalski
    5:28 17 Jul '06  
    I believe that it is a bit simpler to use than log4net, and has some features that log4net is lacking. CodeProject has an article on it:

    http://www.codeproject.org/csharp/nlog.asp

    Jaroslaw Kowalski
    http://blog.jkowalski.net/
    GeneralRe: Have you seen NLog?
    Suman Kumar
    20:24 20 Jul '06  
    Definitely Nlog is good alternative & I appreciate your work. Only the difference I see at this point of time is that log4net is more stable and widely used.
    Generallog4net sample
    Rujith Anand
    22:34 16 Jul '06  
    This is not working for me ??
    GeneralRe: log4net sample
    Suman Kumar
    22:52 16 Jul '06  
    What problem you are facing? Can you provide me the error message?
    AnswerRe: log4net sample
    Suman Kumar
    8:09 17 Jul '06  
    A small change is required if you are using log4net ver. 1.2.10
    Change below line written in AssemblyInfo.cs

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

    to

    [assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch=true)]

    I used version 1.2.0.30507 of log4net for above article.


    Last Updated 14 Jul 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010