建议的方法之一是使用依赖注入将记录器注入到类的构造函数中。 https://docs.asp.net/en/latest/fundamentals/logging.html
但是,如果我的类没有在DI容器中注册,或者我只是想为每个类创建一个静态记录器,那该怎么办呢? 我怎样才能访问在Startup.cs中配置的LoggerFactory?
这就是我使用nlog做的方法:
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();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();最满意答案
您可以在Startup定义一个静态属性,公开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) { //.. } }然后在需要记录器的地方访问它:
public class MyClass { private static readonly ILogger _log = Startup.LoggerFactory.CreateLogger<MyClass>(); //.. }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>(); //.. }更多推荐
发布评论