Background

At a client site that I am at they are coming from a Java background, so we're using a lot of 3rd party .Net libraries etc. that step from their Java counterparts.  Once such library is Log4Net, which in case you don't know, is a logging library that lets you log messages from you apps to a variety of different sources.  A few of the sources are text files, MS SQL, Oracle, SQL Lite, SMTP, etc.  Check out the Log4Net site for a list of all the options which you can log to. 

What I've come to find as of late though is that once you get these libraries working, they work great and can really add benefit to your applications.  BUT I've found setting up these libraries can be a royal pain in the ass, not to mention take quite a few hours before you get them working correctly.  Originally I was blaming the libraries for their confusing documentation, lack of "beginner" explanation etc.  The more I think about it though the more I tend to think that it has something to do with .NET as well.  Since there are so many different project types (Web apps, Console Apps, WinForms apps, etc.) and configuration methods, it is hard to provide examples/setup information for all the different project types.

 

Required Files

First you'll have to grab the latest version of Log4Net (at the time of this posting it was log4net 1.2.10)

 

Installation

Extract the zip file to a location of your liking

 

Project Setup

Web Application Example

  • Create a new Web Site (or Web Application)
  • Right click on the solution and select "Add Reference"
  • Select the log4net.dll under the following directory ..\log4net-1.2.10\bin\net\2.0\release
  • Right click on the reference you just added, log4net.dll, and under properties make sure that "Copy Local" is set to true (this is the step that I knew, but forgot to do and caused myself a huge headache)
    • If you installed log4net into the GAC, this step would be unnecessary
  • Add a configuration section into your Web.Config
  • This will instruct ASP.NET to use the log4net library to read the configuration information you will put further down in the <log4net> section
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  • Add the following below your <configSections>  The point here is to create the information that log4net will read and use to configure itself and the type of logging mechanism you want to use (in this example, we're using a RollingFile appender)
<log4net>    
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="c:\temp\web.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <maxSizeRollBackups value="10" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %level %logger - %message%newline" />
    </layout>
  </appender>
 
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>
  • There are 2 sections here to mention
    • <appender>
      • This tells log4net which logging mechanism to use, in our case we're using a RollingFile appender and specifying the file to log to, "C:\temp\web.log"
      • We also specify how large for the file to grow before it "Rolls", meaning that it will create a new file.
      • I won't get into the <conversionPattern> settings right now, check the documentation on the log4net site for more details
      • You will most likely have to give the ASPNET account modify permissions to the directory.
    • <root>
      • This sets the "defaults" for log4net
      • We specify that log4net should log "ALL" messages.  We could also just specify "DEBUG,INFO,WARN,ERROR,FATAL"
      • In addition to the level, we specify that the default appender to use is the "RollingFile" that we specified above.
  • adf
  • Now that we've setup all the configuration information we can go ahead and start logging inside our application

using log4net;
 
namespace Log4NetTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //tell log4net to load the configuration, it will load the configuration info from the web.config, ideally this should be in the global.asax
                log4net.Config.XmlConfigurator.Configure();
 
                //get an instance of the logger so that we can log our messages to it.
                //it will log to which every logging mechanism you setup in the web.config
                ILog log = LogManager.GetLogger(typeof(_Default));
 
                if(log.IsDebugEnabled)
                    log.Debug("This is a debug message");
            }
            catch (Exception ex)
            {                
                throw;
            }
            
        }
    }
}

  • Now just run your app and once it runs you should have a file named "web.log" in your c:\temp directory.

The weird thing about log4net is that it really doesn't tell you in any way shape or form that its not setup or working correctly.  Here are a few things to check

  • Set a breakpoint on the "ILog log = LogManager.GetLogger(typeof(_Default));" line, if you view log in the quick watch, if "IsDebugEnabled", etc. are ALL set to false, then you know something isn't working correctly
  • Check permissions on the directory where your trying to write the log file to, make sure that ASP.NET has modify permissions on the directory
  • Make sure that log4.net.dll is in the bin directory of your application.  Check the properties of the reference and make sure that "Copy Local" is set to true

Ideally you'll want to configure and start the logger when the web applicaiton loads, so you should move the line "log4net.Config.XmlConfigurator.Configure();" into the Application_load event of the global.asax file.  This will ensure that the logger is always started and ready to log to.  Also, instead of the line "ILog log = LogManager.GetLogger(typeof(_Default));" you should move that as a global variable to your class like so "private static readonly ILog log = LogManager.GetLogger(typeof(_Default)); ".

 

There are a LOT of options with log4net that I didn't even come close to covering.  Check out the documentation as well as experiment a bit yourself and see how you can fit log4net into your application for your logging needs.

 

See code sample below for a pre-setup example.

 

      Windows Application Example

      Coming Soon...

      Console Application Example

      Coming soon...

       

      Log4NetTest.zip (109.71 kb)


      Posted in:   Tags:

      Comments


      January 30. 2008 22:43
      bhup
      this log4netest is not running on .net 2005......???

      http://www.systematixtechnocrates.com/http://www.systematixtechnocrates.com/


      March 8. 2008 18:24
      Cal Jacobson
      Thanks for posting this, Tony!  For some reason, I was having a bear of a time getting log4net up and running in my app and your examples were just what I needed.

      http://blog.caljacobson.com/http://blog.caljacobson.com/


      January 24. 2010 15:15
      bathrooms designs
      Hi

      Great choice for you to use BlogEngine.Net platform for your blog. I love blogengine too because its easy for me as newbie.
      Happy writing

      Regards,
      Joel

      http://www.bathroomvanityfurniture.net/bathrooms-designs.htmhttp://www.bathroomvanityfurniture.net/bathrooms-designs.htm


      January 25. 2010 07:15
      cash advance
      There is no greatness without a passion to be great, whether it's the aspiration of an athlete or an artist, a scientist, a parent, or a businessperson.

      http://cashusloans.com/http://cashusloans.com/


      January 27. 2010 16:30
      visage
      Excellent article you made. I feel enjoy to read your post. Keep writing.

      regards
      dave

      http://www.visagesalonjax.com/http://www.visagesalonjax.com/


      February 1. 2010 01:13
      stretchmark
      Your posting very useful for me
      thanks and keep writing.

      happy blogging

      http://fruitbuzz.com/stretch-mark-removalhttp://fruitbuzz.com/stretch-mark-removal


      February 1. 2010 08:06
      Loans in Rhode Island
      One that would have the fruit must climb the tree.

      http://superpaydayloan.com/state/Rhode-Islandhttp://superpaydayloan.com/state/Rhode-Island


      February 1. 2010 17:35
      colon cleanse reviews
      thanks for posting this great article.
      I'm feel enjoy in your site.
      Happy blogging.


      http://fruitbuzz.com/colon-cleanse-reviewshttp://fruitbuzz.com/colon-cleanse-reviews


      February 8. 2010 01:14
      pabx panasonic
      very nice thank's Smile

      http://djayabersama.com/http://djayabersama.com/


      February 8. 2010 05:26
      cash loans
      Think for yourself and let others enjoy the privilege of doing so too.

      http://cashusloans.com/cash-advance.htmlhttp://cashusloans.com/cash-advance.html


      February 9. 2010 02:53
      no fax payday loans
      He who fears being conquered is sure of defeat.

      http://fastloansus.com/PaydayLoans/no-fax-payday-loans.htmlhttp://fastloansus.com/PaydayLoans/no-fax-payday-loans.html


      February 10. 2010 04:05
      visage
      excellent.
      great article you made. I feel enjoy while reading your article.

      thanks

      http://www.visagesalonjax.com/http://www.visagesalonjax.com/

      Search Blog

      Blog Roll

        OPMLDownload OPML file

        Recent Comments

        Banners

        Theme Grabber
        Disclaimer
        The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

        © Copyright 2010 Tony Testa's World