无论我如何配置appsettings.json和appsettings.Development.json,除非我手动将ConfigureLogging添加到WebHostBuilder设置中,否则我无法在Information消息下方记录任何内容。
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Debug))
.Build();
所以现在我想根据环境动态设置日志级别,但是在使用对我的Startup类的引用设置WebHostBuilder之前,无法找到如何访问IHostingEnvironment实例的方法。
我看到这里有一篇帖子,其中包含类似以下代码的内容,但是在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