gpt4 book ai didi

c# - .Net Core 2.0 调试日志记录被破坏(仍然)

转载 作者:行者123 更新时间:2023-11-30 17:31:41 30 4
gpt4 key购买 nike

无论我如何配置我的 appsettings.jsonappsettings.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() 设置 WebHostBuilder 之前访问 IHostingEnvironment 实例引用我的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

最佳答案

现在,我已经使用了环境变量:

var loggingLevel = LogLevel.Information;
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (env != null && env.ToLower().Equals("development"))
loggingLevel = LogLevel.Debug;

关于c# - .Net Core 2.0 调试日志记录被破坏(仍然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563866/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com