ASP.NET Core Web API Logging from a Static Class

JohnC picture JohnC · Feb 8, 2018 · Viewed 18.2k times · Source

I'm logging just fine using dependency injection on my controllers, now I need to log something from a static class.

How can I log from a static class?

I can't use dependency injection because it's static and I can't just pass in an existing logger object to the static class because it would have the wrong name of class in the log file.

In other words how can I get a logger from the loggerfactory inside my static class?

I came across a similar question and they pointed to an article on a loggerfactory in a static class but that doesn't actually work as I can't get a new logger from it because it won't accept a static class as the parameter:

"Static types cannot be used as type arguments"

Answer

JohnC picture JohnC · Jun 1, 2018

Solution is to have a static reference to the LoggerFactory in a utility static class initialized on startup:

/// <summary>
    /// Shared logger
    /// </summary>
    internal static class ApplicationLogging
    {
        internal static ILoggerFactory LoggerFactory { get; set; }// = new LoggerFactory();
        internal static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>();        
        internal static ILogger CreateLogger(string categoryName) => LoggerFactory.CreateLogger(categoryName);

    }

Which you intialize on Startup.cs:

 public Startup(ILogger<Startup> logger, ILoggerFactory logFactory, IHostingEnvironment hostingEnvironment)
        {
            _log = logger;
            _hostingEnvironment = hostingEnvironment;
            Util.ApplicationLogging.LoggerFactory = logFactory;//<===HERE

        }

Then you can build a logger to use from your static class like so:

internal static class CoreJobSweeper
    {
        private static ILogger log = Util.ApplicationLogging.CreateLogger("CoreJobSweeper");