Wednesday, November 15, 2006

Using log4net

log4net is my recommended lightweight tool for emitting log statements from .NET code. I'm a firm believer that application users shouldn't see exception messages or stack traces - that information is for system administrators and developers only. I like storing log information in a database or in a text file on the server and allowing developers to view it when things start to go pear shaped.

Here's how I typically set up log4net on a project:

- Create a sub directory within your solution - called 3rdParty - and copy the log4net assembly there. This allows meto store one copy of the assembly, and reference it from all projects in the solution.
- Create a separate configuration file that I call log4net.config (I don't use Web.config or App.config)
- Use the XmlConfigurator custom attribute on the assembly that will be loaded first
(Don't forget to set the Watch property to true)
- Start appreciating the benefits of logging!

NOTE 1: If you do choose to use Web.config or App.config, the only reason you have to declare the IgnoreSectionHandler is for .NET to ignore the log4net section!

NOTE 2: No, I don't know what line of code causes the XmlConfiguratorAttribute to be reflected and subsequently configured.

1 comment:

Jono said...

This is the bit that caught me out on a number of occasions: the first time that LogManager.GetLogger() is called, it selects a repository based on the calling assembly. A new default repository will be created and a call will be made to ConfigureRepository() passing in the calling assembly as a parameter. The default repository uses reflection to determine whether any ConfiguratorAttribute has been applied to the calling assembly. NB. If the call to GetLogger() was made from an assembly other than the one in which you defined the XmlConfiguratorAttribute then log4net will assume that there is no configuration!

Coming soon. Why doesn't it work with .NET 2.0 app.config files, and what exactly is a repository?