Logging from static members with Microsoft.Extensions.Logging

Thanks @chris-pratt and @shad for pointing out that the ASP.NET Core loggers approach doesn't play nicely with statics and for actually finding according documentation.

However, there are situations where avoiding statics is difficult or (subjectively) undesirable. So the point of my question was to ask if there was any established pattern for working with the Microsoft.Extensions.Logging in such situations.

The only real answer to that question was in a comment by @alexandre-pires, who pointed me to this Stackify article. Among other things, it shows how to set up a centralized ILoggerFactory that can be used from a static context. However, its conclusion is to just continue using NLog or Serilog and forwarding Microsoft.Extensions.Logging to that library.


DI doesn't play nice with statics. They're sort of opposing design philosophies in one sense. ASP.NET made heavy use of statics (HttpContext, anyone?) and that made using dependency injection very difficult in many respects. ASP.NET Core chose to eschew statics and go with a 100% DI model.

In short, if you want to use dependency injection, your use of statics should dissipate. In most cases this is actually a very good thing. While they can be useful for certain things the are abused and greatly so in most cases. There's no much you can do with a static that you couldn't also do with a dependency injected class in singleton scope, and the latter gives you much greater abstraction and re-usability.

The one use of statics that can't really be replaced is extensions. Of course there's a whole school of thought arguing you should not ever use extensions, anyways. However, if you need or want to have extensions, then you either can't log from those or you'd have to pass in a logger instance as a param. In many cases, having to pass in a logger would severely limit the usefulness of the extension, so you'll likely land on not logging at all. However, even if you're of the school that believes extensions are fine and dandy, most would agree that they should also be limited in scope: i.e. they should just do something simple that doesn't need a lot of code. If that's the case, the need to actually log reduces dramatically.

Long and short, it simply boils down to design decisions you'll have to make. If you want to go the dependency injection route, statics will be a plague on your house, and you should avoid them as such.


You can use Serilog with something like this:

using Serilog;

private static readonly ILogger log = Log.ForContext(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);