Update (11/9/2004 @ 1:50PM EST): Here is a zip file containing a VS.NET solution for this post.
After using this logging solution for the last few months, I finally decided it was time to figure out log4net.
The funny thing is that my initial experience was very similar to this.
The first step (after installing log4net of course) was to get the simplest code running:
// add a reference to the log4net assembly
using System;
using log4net;
using log4net.Config;
public class logTest {
private static readonly ILog _logger = LogManager.GetLogger(typeof(logTest));
public static void Main(string[] args) {
log4net.Config.BaseConfigurator.Configure();
_logger.Debug("This is a debug message");
}
}
Compile and run. By default, all logs are dumped to the console (that’s what the BaseConfigurator.Configure() method is for).
The logs look like:
0 [4720] DEBUG logTest – This is a debug message
log4net has what are called “Appenders”. You can think of these as log message destinations. The default is ConsoleAppender, but log4net ships with about a dozen, including SmtpAppender, FileAppender, AdoNetAppender and many more.
The quickest and easiest way to start using the Appenders is to modify your app.config file.
Adding new appenders is as simple as modifying the config file. If I want the logs to be written to a database, I would add an AdoNetAppender (prereqs: add the table first). You can also change the layout of the logs by modifying your config file as well. In the config file I used for my sample, note this line:
This format is:
date level logger message (and %n is a line-break)
I actually had to dig into the code to find out all the values for the ‘PatternLayout’. You can specify things like class name, method name, line number and thread. Very cool stuff.
The code will need to be modified just a bit:
// add a reference to the log4net assembly
using System;
using log4net;
using log4net.Config;
[assembly: log4net.Config.DOMConfigurator(Watch=true)]
public class logTest {
private static readonly ILog _logger = LogManager.GetLogger(typeof(logTest));
public static void Main(string[] args) {
_logger.Debug("This is a debug message");
}
}
Notice the attribute on the assembly? That tells log4net to find its configuration information in the applications app.config file.
Compile and run and you should see a file named ‘mylog.txt’ in the same directory as the executable file.
More on my log4net experiences in another post.