I'm using log4net in an application for logging.
I want to avoid a discussion about implementing a logging facade, but essentially, I'm creating some classes which will allow an ILog
implementation to be injected via the constructor. Eg:
abstract class MigratorBase<T> : IMigrator<T>
{
private ILog logger;
public MigratorBase(ILog logger)
{
this.logger = logger;
}
}
I also would like to provide a default constructor on the class, which if called, essentially disables logging (or logs to nothing). Instead of scattering fragments of code that check if the logger is null, such as this:
if (this.logger != null)
Log.DebugFormat("Connecting to {0}", this.href);
I thought a better way to accomplish this functionality would be to assign an implementation of ILog
that was purely empty methods. I could call it a NullLog
, and would look similar to this:
class NullLog : ILog
{
public void Debug(object message, Exception exception) { }
public void Debug(object message) { }
public void DebugFormat(IFormatProvider provider, string format, params object[] args) { }
...
...
}
and then in the default constructor I could assign an object of this type to the class's private member, as such:
abstract class MigratorBase<T> : IMigrator<T>
{
private ILog logger;
public MigratorBase(ILog logger)
{
this.logger = logger;
}
public MigratorBase()
{
this.logger = new NullLog();
}
}
This approach seems more object oriented to me, so I think I like it, but googling seems to reveal people suggesting that it's a bad idea to implement an interface with empty methods.
Can anyone suggest why the above might be a bad idea? Or is it in fact an ok idea?