【发布时间】:2017-11-30 00:03:56
【问题描述】:
但是我配置了我的 appsettings.json 和 appsettings.Development.json,除非我手动添加 ConfigureLogging,否则我无法在信息消息下方记录任何内容> 到 WebHostBuilder 设置,如下:
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Debug))
.Build();
所以现在我想根据环境动态设置日志级别,但无法弄清楚如何在我的 Program Main() 中访问 IHostingEnvironment 实例在设置 WebHostBuilder 之前引用我的 Startup 类。
我在这里看到了一个帖子,其中的代码类似于以下内容,但是它在 GetService<Application>() 行上给了我一个语法错误,说 静态类型不能用作类型参数:
var loggingLevel = LogLevel.Information;
IServiceCollection serviceCollection = new ServiceCollection();
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var app = serviceProvider.GetService<Application>();
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
if (hostingEnvironment.IsDevelopment())
{
loggingLevel = LogLevel.Debug;
}
有没有更好的方法来做到这一点?
这是我的 appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Information"
}
},
"Log4Net": {
"ConfigFileRelativePath": "log4net.xml",
"Repository": "NETCoreRepository"
}
}
和appsettings.Development.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug"
}
},
"Swagger": {
"FileName": "MyController.xml"
}
}
而且我项目的调试面板确实设置了环境变量:
ASPNETCORE_ENVIRONMENT Development
【问题讨论】:
-
您可以在这里发布您的 appSettings 吗?这通常定义了最低日志记录级别。
-
好的,添加它们。我尝试了很多组合,例如两者都有“调试”,有各种提供者(控制台等),直到我在 WebHostBuilder 中添加对 ConfigureLogging 的调用之前,没有任何效果。