Using Common.Logging with Caliburn Micro

Caliburn Micro offers several extension points into it, one of which is for logging. For example

LogManager.GetLog = type => new MyLogManager(type);

LogManager.GetLog is a Func and allows us to supply our own logging mechanism.

As you can see, Caliburn Micro includes the interface ILog (the second generic parameter in the Func) for us to implement our own logging code. However I also rather like using the Common.Logging library to abstract the specific logger (i.e. NLog or log4net etc.) from my logging code. So how can we implement our logging using the Common.Logging ?

We just need to implement our own Caliburn Micro ILog and redirect it to the Common.Logging framework. For example

using CommonLogging = global::Common.Logging;
public class CommonLogManager : Caliburn.Micro.ILog
{
   private readonly CommonLogging.ILog log;

   public CommonLogManager(Type type)
   {
      log = CommonLogging.LogManager.GetLogger(type);
   }

   public void Error(Exception exception)
   {
      log.Error("Exception", exception);
   }

   public void Info(string format, params object[] args)
   {
      log.Info(String.Format(format, args));
   }

   public void Warn(string format, params object[] args)
   {
      log.Warn(String.Format(format, args));
   }
}

The code is a little convoluted with namespaces due to ILog existing in both Caliburn Micro and Common.Logging, but unfortunately being different types.

Now just place the following code into the Configure method on your implementation of a Caliburn Micro Bootstrapper

LogManager.GetLog = type => new CommonLogManager(type);