ASP.NET Core Web API Logging from a Static Class

后端 未结 4 528
夕颜
夕颜 2020-12-29 20:58

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

4条回答
  •  有刺的猬
    2020-12-29 21:40

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

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

    Which you intialize on Startup.cs:

     public Startup(ILogger 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");
    

提交回复
热议问题