:-$

Ryan's work blog

My Links

News

The WeatherPixie
Subscribe with Bloglines
About this blog

Tools I use:

Post Categories

Article Categories

Archives

Image Galleries

Blog Stats

Personal

Projects

Random Blogs

Random other

Reference

Web comics

Work

log4net revisited

It's been awhile since I wrote the walkthrough, and I've come across a few more problems and solutions. Most of the walkthrough still applies, but here are two tips to make it even easier.

Connection string management

The connection string for ADONetAppenders is set in the web.config. You usually also have a connection string specified elsewhere for the rest of your application to use, and having to specify it again is a little nasty, but not too bad. The real problem is when you have a dev/test/live database setup. You probably already have some system for swapping your main connection string. The solution is to set the log4net connection string on initialization, and ignore the one specified in web.config.
Instead of just calling:

log4net.Config.DOMConfigurator.Configure();
to initalize log4net, call this:
try{
//configure the damn thing.
log4net.Config.DOMConfigurator.Configure();
log4net.Repository.Hierarchy.Hierarchy h = LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy;
//get the ADO appender
log4net.Appender.ADONetAppender ado = h.Root.GetAppender("ADONetAppender") as log4net.Appender.ADONetAppender;
ado.ConnectionString = YOUR_CONNECTION_STRING;
ado.ActivateOptions();
return conn;
}catch(NullReferenceException nfe) {
throw new NullReferenceException("log4net configuration could not be completed. \nDo you have your app.config set up properly?", nfe);
}
where YOUR_CONNECTION_STRING is, uh, your connection string. Use a snippet like that in your Application_Start.
If you happen to work with me, I've made this into a library function, so we can use it across projects:
Utils.ConfigLog4netConnection();

Creating your loggers with less typing

Typing:

protected static readonly ILog log = LogManager.GetLogger(typeof(CLASS));
is a bother because typing the name of the class is annoying. Paul Lockwood shared this shortcut after making a presentation on log4net in Atlanta. Copy/Paste is usually the devil, but in this case, I think it's ok.
protected static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Sayeth Mr. Lockwood:
It saves having to find the classname every time you declare log. Reflection will mean slight performance degradation when the static initializer executes but in most apps this is insignificant.
I think the initialization time is extra insignificant with web apps, so that sounds like a plan to me. Thanks to everyone who read and commented on that walkthrough.

posted on Tuesday, May 31, 2005 7:09 PM