问题
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"
回答1:
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");
回答2:
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>()
回答3:
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();
}
}
来源:https://stackoverflow.com/questions/48676152/asp-net-core-web-api-logging-from-a-static-class