Friday, 4 April 2008

Configure log4net only once

log4net is a great logging framework with powerful levels of flexibility. This flexibility can result in complexity when used in larger systems. One key point when using log4net in complex systems is to remember to configure the file to log to just once per process.

The file to log to is configured in the call to log4net.Config.XmlConfigurator.Configure() call this just once per process

In complex and constantly changing systems, it isn't always clear whether log4net has been configured. One option is 'if in doubt leave it out', and if you get no logging you know to add the configuration call. But the smart ones out there might disagree with this approach - just as I do! I prefer to just check log4net to see if it is configured before attempting to configure it:

// Only configure log4net once per process
if (!log4net.LogManager.GetRepository().Configured)
{
    // Call log4net.Config.XmlConfigurator.Configure();
    
    if (log.IsDebugEnabled)
    {
       log.DebugFormat("Loaded log4net config in {0}.", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Assembly.FullName);
    }
}
else
{
    if (log.IsDebugEnabled)
    {
       log.DebugFormat("log4net already configured for {0}.", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Assembly.FullName);
    }
}

Some people might see the immediate logging as unnecessary, but I like to add it so I have a visible record that log4net is correctly configured.

6 comments:

neilsgroupie said...

until i figured out how to "Configure log4net only once" my life was empty. thats for enriching it neil :) XXX

bryan said...
This comment has been removed by the author.
bryan said...

Hey Neil,

Interesting that you're checking to see if the repository has been configured already. However, if you're using configuration attributes, the call to XmlConfigurator.Configure() is completely unnecessary.

p.s. sorry about the add/remove comments, had to fix a typo.

Neil kilbride said...

Bryan,

As far as I can tell your method works for log4net if the config is in an expected location.

For the work this relates to, a master configuration file is used that is shared across numerous web apps, services, com+ components. So I think I still need to load up the configuration XML and .Configure log4net:
// Log4NetConfig is XmlElement with configuration details
if (!log4net.LogManager.GetRepository().Configured)
{
log4net.Config.XmlConfigurator.Configure(Log4NetConfig);
}

Neil kilbride said...

But I do like what you've done Bryan, I may even make a blog post referencing your post for reference if you don't mind?

bryan said...

Please do. :-)