c# - 控制台应用程序中的 .NET Core 日志记录 - 详细信息级别
问题描述
我正在.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 = services.GetService<ILogger<MyService>>();
现在,如果我执行此代码:
_logger.LogInformation("info");
_logger.LogError("error");
两条消息都打印到控制台,似乎它没有从 appsettings.json 中获取设置。
我在互联网上搜索了很多,但找不到解决方案。
解决方案
通过调用 AddConsole(),您将覆盖来自 AddConfiguration() 调用的设置(使用默认值,因为您没有在 AddConsole 调用中提供任何设置)。
推荐阅读
- elasticsearch - 布尔查询中双重嵌套字段的内部命中
- ios - 使用 xcode 10 beta 构建失败
- rx-java2 - RxJava Completable 的 Emitter.onComplete 发生在 Observer 的回调之前吗?
- windows - 删除与 csproj 文件同名的文件夹
- c# - 从 C# 代码将 SSIS 包作为 SQLAgent 作业执行,并将参数传递给 SSIS 包
- java - GXT 主题替换停止工作
- vue.js - 使用全局语言参数构建路由器链接
- logging - 实时数据分析
- shopify - Shopify 在条件下显示集合描述
- mongodb - 找不到数据源:com.mongodb.spark.sql.DefaultSource