本文介绍了如何使用 ConsoleLoggerProvider 创建 LoggerFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConsoleLoggerProvider 有四个构造函数:

  1. ConsoleLoggerProvider(IConsoleLoggerSettings)
  2. ConsoleLoggerProvider(IOptionsMonitor)
  3. ConsoleLoggerProvider(Func, Boolean)
  4. ConsoleLoggerProvider(Func, Boolean, Boolean)

其中三个已被此消息声明为过时:

Three of them are declared obsolete with this message:

此方法已过时,将在未来版本中删除.推荐的替代方法是使用 LoggerFactory 配置过滤和 ConsoleLoggerOptions 配置日志选项.

使用构造函数 #3,创建带有 ConsoleLoggerProviderLoggerFactory 很简单(如 实体框架核心 - 日志记录):

With constructor #3, creating a LoggerFactory with a ConsoleLoggerProvider is straightforward (as documented on Entity Framework Core - Logging):

var loggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider((category, level) => level >= LogLevel.Information, true) });

但由于它已被弃用,我们只剩下构造函数 #2.这是我发现的等效项:

But since it's deprecated, we are left with constructor #2. Here's what I found to be equivalent:

var configureNamedOptions = new ConfigureNamedOptions<ConsoleLoggerOptions>("", null);
var optionsFactory = new OptionsFactory<ConsoleLoggerOptions>(new []{ configureNamedOptions }, Enumerable.Empty<IPostConfigureOptions<ConsoleLoggerOptions>>());
var optionsMonitor = new OptionsMonitor<ConsoleLoggerOptions>(optionsFactory, Enumerable.Empty<IOptionsChangeTokenSource<ConsoleLoggerOptions>>(), new OptionsCache<ConsoleLoggerOptions>());
var loggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider(optionsMonitor) }, new LoggerFilterOptions { MinLevel = LogLevel.Information });

这看起来太复杂了,我是不是漏掉了一些更简单的东西?

This seems overly complicated, am I missing something simpler?

推荐答案

在 .NET Core 2.2 中,您可以通过 Microsoft 的依赖注入框架构建 ILoggerFactory 而无需使用过时的方法.它比一切都是手工构建的版本要简洁一些.方法如下:

In .NET Core 2.2, you can build an ILoggerFactory without using obsolete methods through Microsoft's dependency injection framework. It's a little less verbose than the version where everything is constructed by hand. Here’s how:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder => builder
    .AddConsole()
    .AddFilter(level => level >= LogLevel.Information)
);
var loggerFactory = serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>();

在 .NET Core 3.0 中,您可以使用 LoggerFactory.Create:

And in .NET Core 3.0, you can use LoggerFactory.Create:

var loggerFactory = LoggerFactory.Create(builder => {
        builder.AddFilter("Microsoft", LogLevel.Warning)
               .AddFilter("System", LogLevel.Warning)
               .AddFilter("SampleApp.Program", LogLevel.Debug)
               .AddConsole();
    }
);

另见:

这篇关于如何使用 ConsoleLoggerProvider 创建 LoggerFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 11:58