如何在ASP.NET 5中访问记录器(How to access logger in ASP.NET 5)

编程入门 行业动态 更新时间:2024-10-27 08:36:22
如何在ASP.NET 5中访问记录器(How to access logger in ASP.NET 5)

建议的方法之一是使用依赖注入将记录器注入到类的构造函数中。 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>(); //.. }

更多推荐

本文发布于:2023-08-07 12:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:记录器   如何在   ASP   NET   access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!