I'll admit it - I first encountered NullLogger in code generated by an AI coding assistant. At first glance, I almost dismissed it as one of those "AI quirks," but then I realized it was actually a real class available in the .NET Framework that I'd been missing out on.
What is NullLogger?
NullLogger is part of Microsoft.Extensions.Logging and implements the null object pattern for logging. It's a logger that does absolutely nothing - all of its methods are no-ops. While that might sound useless at first, it's actually quite valuable.
Imagine you have the following code:
Now when testing this code I would normally mock the logger, but thanks to the built-in NullLogger I no longer have to do that:
How to use it
In the example above I showed the typical way to get an ILogger<T> instance. There is also a non-generic one to create an ILogger instance:
Both are singletons, so you're always getting the same instance - no memory overhead from creating multiple null loggers.
Conclusion
Sometimes the best learning moments come from unexpected sources. The NullLogger is a simple but elegant solution to a common problem, and I'm glad AI-generated code introduced me to it. By embracing the null object pattern, it helps you write cleaner, more maintainable code without sacrificing the flexibility to make logging optional.
More information
NullLogger Class (Microsoft.Extensions.Logging.Abstractions) | Microsoft Learn
