我如何从ASP.NET Core中的控制器以外的其他类登录? [英] How do I log from other classes than the controller in ASP.NET Core?

查看:148
本文介绍了我如何从ASP.NET Core中的控制器以外的其他类登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET Core内置了对日志记录的支持,但是文档指出应通过依赖注入请求ILogger来完成日志记录,即将其作为参数添加到Controller构造函数中.

ASP.NET Core has built-in support for logging, but the documentation states that logging should be done by requesting an ILogger via dependency injection, i.e. by adding it as an argument to the Controller constructor.

在我的代码中使用ILogger参数污染方法签名或构造函数,对于这种横切关注的问题,感觉像是错误的解决方案.在Android中,Log类是静态的,因此从代码的任何部分进行记录都很简单.

Polluting method signatures or constructors throughout my code with ILogger arguments feels like the wrong solution for this cross-cutting concern. In Android the Log class is static, making it trivial to log from any part of the code.

从控制器以外的其他地方进行日志记录的好方法是什么?

What would be a good way to do logging from other places than the controller?

推荐答案

关于使用任何组件登录:

Regarding using logging in any component:

通过依赖注入请求ILoggerFactoryILogger<T>来向应用程序中的组件添加日志.如果请求ILoggerFactory,则必须使用其CreateLogger方法创建记录器.

Adding logging to a component in your application is done by requesting either an ILoggerFactory or an ILogger<T> via Dependency Injection. If an ILoggerFactory is requested, a logger must be created using its CreateLogger method.

如果您的CustomClass是数据容器(DTO类),则它应该不了解日志记录,而只包含数据.

If your CustomClass is a data container (DTO class), it should not know about logging, but just contain data.

对于其他名称如"Service","Provider","Handler"等的类,最佳实践是使用依赖注入来解析实例.通常,应尽可能使用DI,因为这是一种实现对象及其协作者或依赖关系之间松散耦合的技术.有关更多信息,以下问题可能很有趣:我应该使用依赖注入还是静态工厂?

For other classes with names like "Service" , "Provider", "Handler" and so on, the best practices is to resolve instances using dependency injection. In general, you should use DI wherever it is possible, as it’s a technique for achieving loose coupling between objects and their collaborators or dependencies. For more information, the following question might be interesting: Should I use Dependency Injection or static factories?

因此,只需将ILogger<CustomClass>添加到其构造函数中(实际上与对控制器相同),因为.NET Core默认仅支持构造函数注入:

So simply add ILogger<CustomClass> to its constructor (actually the same way, as you do for controllers), as .NET Core supports only constructor injection by default:

public class CustomClass
{
    private readonly ILogger _logger;

    public CustomClass(ILogger<CustomClass> logger)
    {
        _logger = logger;
    }
}


ASP.NET Core的内置依赖项注入容器将自动解决瞬态依赖项.因此,如果您的控制器将类A作为依赖项使用类B作为您要在其中记录某些内容的依赖项,则您的代码可以是这样的:


ASP.NET Core’s built-in dependency injection container will automatically resolved transient dependencies. So if your controller has class A as a dependency that uses class B where you want to log something, your code can be something like this:

public class MyController
{
    public MyController(ClassA classA)
    { ... }
}

public class ClassA
{
    public ClassA(ClassB classB)
    { ... }
}

public class ClassB
{
    private readonly ILogger _logger;

    public ClassB(ILogger<ClassB> logger)
    {
        _logger = logger;
    }

    public void DoSomethingWithLogging()
    {
        // use _logger
    }
}

请注意,您还需要使用IServiceCollection.Add…方法在Startup中注册依赖项:

Note that you also need to register the dependencies in Startup using IServiceCollection.Add… methods:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddTransient<ClassB>();
    services.AddTransient<ClassA>();
}


内置日志记录支持意味着开箱即用的.NET Core知道并正在使用内置抽象进行日志记录.这主要是通过ILoggerFactoryILoggerProvider接口完成的.


Built-in logging support means that .NET Core out of the box knows about and is using built-in abstractions for logging. This is mainly done by ILoggerFactory and ILoggerProvider interfaces.

/// <summary>
/// Represents a type used to configure the logging system and create instances of <see cref="ILogger"/> from
/// the registered <see cref="ILoggerProvider"/>s.
/// </summary>
public interface ILoggerFactory : IDisposable

// <summary>
/// Represents a type that can create instances of <see cref="ILogger"/>.
/// </summary>
public interface ILoggerProvider : IDisposable

使用您自己的ILoggerProvider实现,您可以添加自己的记录器,该记录器可以执行您想要执行的任何操作.您可以检查 NLog 记录器的实现作为工作示例.

Using your own ILoggerProvider implementation, you can add your own logger that can do whatever you want. You can check the NLog logger implementation as working example.

感谢ILoggerFactory,您可以仅出于特定项目目的配置Logger:

And thanks to ILoggerFactory, you can simply configure your Logger for project-specific purposes:

要在ASP.NET Core应用程序中配置日志记录,应在Startup类的Configure方法中解析ILoggerFactory.当您将这种类型的参数添加到Configure方法中时,ASP.NET Core将使用依赖注入自动提供ILoggerFactory的实例.

To configure logging in your ASP.NET Core application, you should resolve ILoggerFactory in the Configure method of your Startup class. ASP.NET Core will automatically provide an instance of ILoggerFactory using Dependency Injection when you add a parameter of this type to the Configure method.

这篇关于我如何从ASP.NET Core中的控制器以外的其他类登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆