问题描述
我在我的控制器上使用依赖注入来记录日志就好了,现在我需要记录一些来自静态类.
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"
推荐答案
解决方案是在启动时初始化的实用程序静态类中对 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!