gpt4 book ai didi

c# - 如何使用 ConsoleLoggerProvider 创建 LoggerFactory?

转载 作者:行者123 更新时间:2023-12-02 12:25:38 30 4
gpt4 key购买 nike

ConsoleLoggerProvider有四个构造函数:

  1. ConsoleLoggerProvider(IConsoleLoggerSettings)
  2. ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions>)
  3. ConsoleLoggerProvider(Func<String,LogLevel,Boolean>, Boolean)
  4. ConsoleLoggerProvider(Func<String,LogLevel,Boolean>, Boolean, Boolean)

其中三个已被声明为过时,并显示以下消息:

This method is obsolete and will be removed in a future version. The recommended alternative is using LoggerFactory to configure filtering and ConsoleLoggerOptions to configure logging options.

使用构造函数 #3,创建 LoggerFactoryConsoleLoggerProvider很简单(如 Entity Framework Core - Logging 中所述):

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

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

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 });

这看起来过于复杂,我是否缺少一些更简单的东西?

最佳答案

Microsoft.Extensions.Logging 3.0+,你可以使用更简单的LoggerFactory.Create :

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

对于 Microsoft.Extensions.Logging 版本 2.2+,您可以通过 Microsoft 的依赖项注入(inject)框架构建 ILoggerFactory,而无需使用过时的方法。它比 2.1 版本稍微简洁一些,在 2.1 版本中,所有内容都是手工构建的。方法如下:

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

另请参阅:

关于c# - 如何使用 ConsoleLoggerProvider 创建 LoggerFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690820/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com