如何在ILogger中使用appsettings.json中定义的记录器配置



我有一个应用程序,包含以下appsettings.json文件,其中包含日志配置:

{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore": "Warning",
"Microsoft.EntityFrameworkCore.Database": "Warning"
},
"Console": {
"FormatterName": "Console",
"FormatterOptions": {
"SingleLine": true,
"IncludeScopes": true,
"TimestampFormat": "yyyy-MM-ddTHH:mm:ss.fffffffK : ",
"UseUtcTimestamp": true
}
}
}
}

我用这种方式创建记录器实例(不使用IHost等(

ILogger logger = new LoggerFactory().CreateLogger<Program>();

所以我的问题是如何让Ilogger使用appsettings.json中的配置?

ILoggerFactory设计用于依赖项注入,您通常会使用IServiceCollection.GetService<ILoggerFactory>()而不是new LoggerFactory(),并且在主机设置中,您会挂接该GetService的配置。

如果你能使用它,那就更好了,因为.NET服务设置已经有了配置,并且优化得很好。默认情况下,它内置了控制台支持。

如果没有它,您就无法访问您调用以获取配置的GetServicehostingContext.Configuration.GetSection("Logging")。你必须自己设置。

首先获取配置:

// Read the app settings file, you can add secrets and additional files here
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
// Build the configuration
var configuration = builder.Build();
// Load the section for the logger
var loggingConfig = configuration.GetSection("Logging");

现在,每次您致电new LoggerFactory()时,都需要与您想要写信给的提供商进行设置:

// Create the factory
var factory = new LoggerFactory();
ILoggerProvider yourCustomProvider = // whatever you want to do here, using your loggingConfig 
// Add your custom provider
factory.AddProvider(yourCustomProvider);

然后,无论何时调用factory.CreateLogger<...>();,都会得到一个输出到提供者的ILogger

最新更新