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