Thursday, 20 December 2007

Logging with log4net and NUnit

This is a reoccurring problem that I forget how to solve:

The problem
  • A class under test contains useful logging.
  • Your class configures logging using an assembly attribute:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
  • It is being tested via the nunit-console or gui and you want to see the output of the log messages.
What's going on
When using assembly attributes to configure log4net, logging is configured by the first such attribute that is loaded (more in the log4net faq). As NUnit uses log4net, it gets there first. By default, NUnit has logging switched off, hence no log messages are emitted.

The solution
As hinted in the log4net faq, you can also load configure logging programatically, whenever and wherever you wish. So...
  1. Include a log4net configuration file in your Unit test project (as app.config, or a separate log4net.config).
  2. Load this file at the start of your test run. See my post on the NUnit SetupFixture for more details.

1 comment:

GaussC said...

If you have a lot of namespaces or you are looking for alternative solution please look here. Except alternative solution I described how to test log4net configuration (yes! this should be tested too :-)