I’ve been using log4net in a recent project, and recently needed to modify things so that the log file can be changed at runtime. It’s being used with a console application, and the log filename needs to change depending on what the command line parameters are.
There’s a great entry about setting the log file location at runtime with a DOM configured log4net, which explains how to do this. In my case, I’ve used a rolling file appender, and implemented things a little differently, though the concept is the same.
I’ve put together a basic console application showing how this works, which you can download.
It’s a simple console application, where log4net is configured from an external configuration file. The main things to look at are the file and datePattern settings. Using the standard RollingFileAppender, this will creates logfiles in the Logs directory, named Log-yyyy-mm-dd.log.
The custom RollingFileAppender class adds a static property called prefix. When set, the log filename will change to Log-Prefix-yyyy-mm-dd.log. To set the prefix, you simply need to set the Prefix property, before initialising the log object.
RollingFileAppender.Prefix = "MyPrefix";
ILog logger = LogManager.GetLogger(typeof (MyClass));
logger.Debug("A debug message");
Overall, I’m really impressed with log4net. It’s a solid logging framework, and makes it much easier to add logging to applications. It’s simple to implement, and a lot more convenient than rolling your own logging system.