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
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.
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>()
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");
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();
}
}