You can stop mocking ILogger
Posted on Saturday, 1st June 2019
Just a quick post, nothing technically challenging but hopefully valuable to some none the less.
It all started a couple of days ago when I found myself browsing through Microsoft’s Logging Abstractions library source code. For those that aren’t familiar with this library the aim of it (as the name suggests) is to provide a set of abstractons over the top of common APIs that have emerged around logging over time (take ILogger
for instance).
As I was reading the source code I noticed the library contains an implementation of the common ILogger
inferface called NullLogger
. “Great!” I thought, “I really don’t like mocking and now I don’t need to mock ILogger anymore!”
Initially I thought this was old news and I’d somehow missed the memo, so I swiftly moved on. But given the number of likes and retweets a tweet of the discovery I made received I thought it would be valuable to write a short post as a nod of its existence for anyone who hasn’t seen it yet.
Logger.Instance
As you can see the implementation of the class is very straight forward, it does nothing at all…
public class NullLogger : ILogger
{
public static NullLogger Instance { get; } = new NullLogger();
private NullLogger()
{
}
public IDisposable BeginScope<TState>(TState state)
{
return NullScope.Instance;
}
public bool IsEnabled(LogLevel logLevel)
{
return false;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
}
}
However it does mean that if the project I’m working on depends on this this library (which most on .NET Core will be doing) I can start to use instances of NullLogger
instead of mocking ILogger
.
It doesn’t stop at ILogger
either, there are also implementation of ILogger<T>
in there (unsurprisingly called NullLogger<T>
) and NullLoggerFactory
.
Great, thanks Microsoft!
Enjoy this post? Don't be a stranger!
Follow me on Twitter at @_josephwoodward and say Hi! I love to learn in the open, meet others in the community and talk Go, software engineering and distributed systems related topics.