Reputation: 9516
One of the suggested approaches is to use Dependency Injection to inject logger to the constructor of the class. https://docs.asp.net/en/latest/fundamentals/logging.html
However, what if my class is not registered with DI container or I just want to create a static logger per a class. How can I still access LoggerFactory which was configured in Startup.cs?
This is how I would do it using nlog:
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
Upvotes: 2
Views: 1274
Reputation: 4010
You could define a static property in your Startup
which exposes the LoggerFactory
:
public class Startup
{
public Startup(ILoggerFactory loggerFactory)
{
LoggerFactory = loggerFactory;
}
public static ILoggerFactory LoggerFactory { get; set; }
public void ConfigureServices(IServiceCollection services)
{
//..
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//..
}
}
And then access it where you need a logger:
public class MyClass
{
private static readonly ILogger _log = Startup.LoggerFactory.CreateLogger<MyClass>();
//..
}
Upvotes: 4