Thursday, December 18, 2008

A Simple Log4Net Setup

I've been helping out a co-worker with using Log4Net in an ASP.NET web application. It is really simple once you get the hang of it. If you're having problems setting up Log4Net, go with this simple step-by-step approach.

Step 1: Add a reference to the Log4Net dll

Step 2: Add this to your Global.asax

protected void Application_Start(object sender, EventArgs e)

Step 3: Add this to the configSections of your web.config

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Step 4: Add this after the end of the configSections tag

<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="C:\Log4Net.log" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />

<level value="All" />
<appender-ref ref="LogFileAppender" />

Step 5: Add this in your code

log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Run the code and look for the file Log4Net at the root of C drive (configurable in Step 4).

You can add appenders to send out email or log to a remote console, but I'll leave that for another blog post.


Rodney J. Woodruff said...

Of course, you need to remind developers that they should do if(logger.IsDebugEnabled) to prevent the nasty performance drain. The same holds true for Warn.

Nitin R.K. said...



Thank you for your comment.

My objective for this example was to keep the code as short as possible so I kept the code minimal, but I do agree that the logger.Debug (or Warn, Info, ...) should be wrapped within the 'if' statement to check if logging is enabled at that level especially when strings are being created by concatenation and putting in variable values.

Looking forward to hearing more from you.

Merry Christmas!


bryan said...

If you're looking to cut down the amount of code you have to write, consider taking advantage of log4net's configuration attribute.

By using attributes, you'll never need step 2. Check out the article here:
log4net configuration made simple

Nitin R.K. said...

Hi Bryan!

Thanks for your feedback.

The Log4Net library provides several ways to accomplish the same thing. As a good practice, I would say developers ought to use the assembly attribute and keep the Log4Net config in a separate file.


ghkj said...

welcome to the wow power leveling cheap wow power leveling service site, buy cheap wow gold,wotlk gold,world of warcraft power leveling buy wow gold