如何处理依赖注入创建的ILogger范围

时间:2019-04-30 23:02:05

标签: c# logging dependency-injection dispose

我已经在DI类中定义了logger范围

var serviceProvider = serviceCollection.BuildServiceProvider();
var logger =  serviceProvider.GetService<ILogger<Processor>>();

logger.BeginScope(new Dictionary<string, object>
{
    {"system", "MyApplication"},
    {"invocation_id", Guid.NewGuid()}
});

像这样使用记录仪(工作正常)

public class Processor : IProcessor
{
    private readonly ILogger<Processor> logger;

    public Processor(ILogger<Processor> logger)
    {
        this.logger = logger;
    }

    public void LogMessage()
    {
        logger.LogInformation(""Hello World");
        //Dispose Logger
    }
}

完成后如何处置此记录器?

1 个答案:

答案 0 :(得分:0)

BeginScope返回一个IDisposable,它关闭日志记录范围。 通常,我会将操作包装在using语句中。

var serviceProvider = serviceCollection.BuildServiceProvider();
var logger =  serviceProvider.GetService<ILogger<Processor>>();

using (logger.BeginScope(new Dictionary<string, object>
{
    {"system", "MyApplication"},
    {"invocation_id", Guid.NewGuid()}
})) 
{
    IProcessor processor = new Processor(logger);
    ... do your thing
}

这与https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#log-scopes

中的建议相似