by Njål

Configuring Log4net from code!

LOGGING!
Photo: A more traditional way of logging.

The first thing I do when creating a new .NET website/app is to add Log4net. I usually find some old code, and

  1. copy the log4net.dll,
  2. copy the log4net.config
  3. copy the c# code that loads the config file

For a lot of the smaller projects/solutions I am working on – there is no need at all to change log levels / appenders etc. during run time – so I configure log4net directly from my c# code. This means that I can drop the log4net.config file.

Here is a piece of code that creates a simple FileAppender. It can easily be modified to handle RollingFileAppenders etc..


Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/

FileAppender fileAppender = new FileAppender();
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.File = Server.MapPath(“/”) + “log.txt”;
PatternLayout pl = new PatternLayout();
pl.ConversionPattern = “%d [%2%t] %-5p [%-10c] %m%n%n”;
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();

log4net.Config.BasicConfigurator.Configure(fileAppender);

//Test logger
ILog log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug(“Testing!”);

The result of the log test is:
2010-11-13 14:52:46,611 [20] DEBUG [_Default ] Testing!
A good place to put this code is in the entrypoint of your App (the Main(string[] args) method), or in the Global.asax if you are creating a web app (remember to grant the NETWORK SERVICE user write access to the folder you are logging to).

Happy logging!

-N