是否注入ILogger< T>每次创建一个新的记录器? [英] Does injecting ILogger<T> create a new logger each time?

查看:130
本文介绍了是否注入ILogger< T>每次创建一个新的记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档中的日志记录示例中,有一个示例如何将记录器注入控制器:

On the logging samples in the documentation, there is an example how to inject a logger into a controller:

public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }
}

每次将记录器注入到类似此处的内容时,DI框架都会创建一个新的记录器吗?有更好的方法吗?

Does the DI framework create a new logger each time I inject a logger into something like here? Is there a better way?

推荐答案

通过查看源代码很容易回答这个问题.当您执行services.AddLogging()时,默认行为是

This is easily answered by a look into the source. When you do services.AddLogging(), the default behavior is that ILogger<T> is registered as a singleton:

public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure)
{
    // …

    services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

    // …
}

因此,只要应用程序正在运行,就不会保留特定类型TILogger<T>实例.因此,在向控制器中注入ILogger<TodoController>时,每次都会将相同的logger实例传递给它.

So no, ILogger<T> instances for a certain type T are kept around for as long as the application is running. So when injecting an ILogger<TodoController> into your controller, the same logger instance will be passed to it every time.

当然,这仅适用于记录器,而不适用于控制器本身.默认情况下,控制器在DI之外被激活,但在一定范围内有效地存在.因此,对于每个请求,都会有一个新的控制器实例;但是那会从以前获得记录器实例.

Of course this only applies to the logger, but not your controller itself. By default, controllers are activated outside of DI but effectively live with a scoped lifetime. So on every request, there will be a new controller instance; but that one will then get the logger instance from before.

要回答您的最后一个问题,是否有更好的方法?否.除了这一行为已经很不错(因为不需要新的记录程序实例)这一事实之外,使用日志记录的正确方法确实是将ILogger<T>注入到类型T中,因此您得到了正确的分类记录器实例.当后台运行着如此昂贵的事情,而您可能永远不会看到的时候,真的不需要担心这里的超薄记录器;

To answer your last question, is there a better way? No. Apart from the fact that this behavior is already a good one (since there’s no need for new logger instances), the proper way to use logging is indeed to inject ILogger<T> into types T, so you get a properly categorized logger instance. There’s really no need to worry about the very thin logger here when there are so many way more expensive things going on in the background that you will likely never see ;)

这篇关于是否注入ILogger&lt; T&gt;每次创建一个新的记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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