ASP.NET Core Web API Logging from a Static Class

后端 未结 4 529
夕颜
夕颜 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:31

    I found this question with answers useful, but I remembered I already have installed Serilog. Instead of implementing a custom static instance, I could use the default implementation from Serilog.

    It comes with multiple nice logging features with multiple overloaded version.
    Here are two examples:

    using Serilog;
    ...
        Log.Error(myException, "my message");
        Log.Warning("My message", myValue);
    

    Serilog.Log is a static instance that is ready when configured in Program.cs or Startup.cs.

    0 讨论(0)
  • 2020-12-29 21:39

    You can use the static LoggerFactory instance with the following extension method which accepts a regular parameter of type Type, rather than a generic type parameter: CreateLogger(ILoggerFactory, Type)

    i.e. loggerFactory.CreateLogger(typeof(T)) rather than loggerFactory.CreateLogger<T>()

    0 讨论(0)
  • 2020-12-29 21:40

    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");
    
    0 讨论(0)
  • 2020-12-29 21:41

    First of all, I agree with NightOwl888 answer.

    But as an option (consider this as a workaround) you could inject ILogger dependency via method parameter => so a class that will call this static method should be responsible for providing a correct implementation of ILogger.

    static class YourClass
    {
        public static void DoSomething(ILogger logger)
        {
             // do something
             // call log.Log();
        }
    }
    
    0 讨论(0)
提交回复
热议问题