The default ILog interface for log4net only presents forward 7 logging levels (ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF”). In a few projects I have for a long time wanted to a level between INFO and DEBUG. There is information that I would like to log for my purposes, but for others it is simply clutter.
In researching how to write a custom level I started poking around Level.cs and noticed toward the bottom (around line 500) there are already a large number of default logging levels define, its jus that as mentioned above the default ILog interface doesn’t present them forward.
I started considering writing my own ILog implementation but then it hit me, extension methods to the rescue:
public static class ILogExtentions
{
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Trace(this ILog log, string message, Exception exception)
{
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
log4net.Core.Level.Trace, message, exception);
}
public static void Trace(this ILog log, string message)
{
log.Trace(message, null);
}
public static void Verbose(this ILog log, string message, Exception exception)
{
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
log4net.Core.Level.Verbose, message, exception);
}
public static void Verbose(this ILog log, string message)
{
log.Verbose(message, null);
}
}
These extension methods should probably actually go on ILogger, (which as you can see above is where the actual Log method is) but since I always use the default ILog implementation this makes calling the methods feel more natural.
Now I can simply call log.Trace or log.Verbose and get log output. So instead of having a level between DEBUG and INFO, I have just started logging my stuff at a level below debug. Now the technical users can review the DEBUG log without having to see my very fine level messages.
As I mentioned there are a large number of additional levels defined that the same methods could easily be implemented for.
Note: Don’t forget to update your log4net config to turn on these additional levels. I spent a while thinking these methods weren’t working until I figured out I just hadn’t turned them on. Enjoy!