从静态类记录ASP.NET Core Web API [英] ASP.NET Core Web API Logging from a Static Class

查看:415
本文介绍了从静态类记录ASP.NET Core Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用控制器上的依赖项注入来很好地记录日志,现在我需要从静态类中记录.

I'm logging just fine using dependency injection on my controllers, now I need to log something 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.

换句话说,如何从静态类中的loggerfactory中获取记录器?

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

我遇到了一个类似的问题,他们指向静态工厂中有关loggerfactory的文章,但这实际上不起作用,因为我不能从中获得新的logger,因为它不接受静态类.参数:

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"

推荐答案

解决方案是在启动时初始化的实用程序静态类中对LoggerFactory进行静态引用:

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);

    }

您要在Startup.cs上进行初始化:

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");

这篇关于从静态类记录ASP.NET Core Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆