【发布时间】:2021-08-17 18:04:33
【问题描述】:
我正在 .NET Core 5.0 (VS 2019) 中创建控制台应用程序。我无法使用各种日志记录配置来实现我的 appsettings.json。它根本不起作用。
我在Main() 方法的开头有这个来配置appsettings.json:
var dir = Directory.GetCurrentDirectory();
var configurationRoot = new ConfigurationBuilder()
.SetBasePath(dir) // Microsoft.Extensions.Configuration.Json
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: false)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
我还做了 ServiceCollection 扩展来配置 ServiceCollection 中的日志记录:
public static IServiceCollection ConfigureApplicationLogging(this IServiceCollection @this, string appName, IConfigurationRoot configurationRoot)
{
@this.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddConfiguration(configurationRoot);
loggingBuilder.AddConsole();
loggingBuilder.AddEventLog(settings =>
{
settings.LogName = "Application";
settings.SourceName = appName;
});
});
return @this;
}
这就是我创建 ServiceCollection 和构建服务的方式:
var serviceCollection = new ServiceCollection();
serviceCollection.ConfigureApplicationLogging("MyApp", configurationRoot)
// ... add other services
var services = serviceCollection.BuildServiceProvider();
以下是我的 appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Error",
"Microsoft": "Error"
}
},
"EventLog": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Error"
}
}
}
}
如您所见,Console 的默认级别设置为错误。我通过ServiceCollection获取logger:
_logger = services.GetService<ILogger<MyService>>();
现在,如果我执行这段代码:
_logger.LogInformation("info");
_logger.LogError("error");
两条消息都被打印到控制台,似乎它没有从 appsettings.json 中获取设置。
我在互联网上搜索了很多,但找不到解决方案。
【问题讨论】:
-
就我个人而言,我碰巧使用了 Log4Net(特别是
NLog.Web.AspNetCore),它与Microsoft.Extensions.Logging结合使用。因此,1)我的“Logging > LogLevel”在appsettings.json(和你的一样),但是2)我的日志接收器在单独的文件nlog.config中定义。 -
好的,太好了。谢谢你的提示。会调查的。
标签: c# .net .net-core console-application