Search code examples
loggingasp.net-core

Logging from static members with Microsoft.Extensions.Logging


According to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging, the suggested way to use Microsoft.Extensions.Logging seems to be via dependency injection of ILogger objects.

What is the suggested pattern in situations where dependency injection doesn't work (or doesn't work well), such as in extension methods, type initializers, static properties, and other static members where passing an ILogger would be very cumbersome?

With log4net (which my team used before), a common pattern is this:

public static class SomeExtensions
{
  private static readonly ILog s_log = LogManager.GetLogger(typeof(SomeExtensions));

  public static void ExtensionMethod (this SomeType someType)
  {
    s_log.Info("...");
  }
}

Is there a similar established or recommended pattern with Microsoft.Extensions.Logging?


Solution

  • 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.