Here at Bambit Technologies, we use log4net in nearly every application that we build, from web sites, to desktop apps to server services. It's well written, easy to implement and extremely versatile. With that said, there's a couple things I would like changed or implemented.
One of the biggest changes I would like to see is when logging an exception. Generally, to log an exception you make a call like this:
ILog myLogger=LogManager.GetLogger();
Exception exception=new Exception("Something happened");
myLogger.Error("Something happened, and it wasn't good", exception);
Pretty straight forward, right?
But what if I want to format the string I am logging, then you have to do the following:
myLogger.Error(string.Format("Something bad happened: {0}", errorString), exception);
Essentially adding a "string.Format" call to the message string. log4net DOES have the method "ErrorFormat", but if you call it like:
myLogger.ErrorFormat("Something bad happened: {0}", errorString, exception);
the actual exception is lost, as it is passed in as an argument to the format string.
For a long time we resigned ourselves to just adding the extra String.Format call, as trying to change the implementation for all the different types of loggers would be a headache at best, not to mention having to test and verify and rebuild everytime a new version of log4net comes out (which, admittedly isn't that often, it's extremely stable)
Extension Methods
Now, with the 3.0 framework, we have a new option: Extension Methods. Extension methods are exactly what they sound like, ways to extend a class with added functionality.
To see how this helps us with log4net, we create an extension class with the new methods we would like to see implemented.
public static Exception Exception(this ILog logger, Exception exception, string fmt,
params object[] args)
{
logger.Error(string.Format(fmt, args), exception);
return exception;
}
To see the complete code listing, see this link
Now, when I need to log an exception, I can simply call:
myLogger.Exception(exception, "Something is definatly wrong: {0}", errorString);
You'll also note that each of these methods returns the exception I pass in. This simply allows us to join everything in one statement:
throw myLogger.Exception(
new Exception("Something is wrong"),
"Something is wrong:", errorString);
which comes in pretty handy.