gpt4 book ai didi

c# - 在生产模式下删除 ASP.NET Core 2.0 中的控制台和调试记录器

转载 作者:IT王子 更新时间:2023-10-29 04:30:19 27 4
gpt4 key购买 nike

在 ASP.NET Core 2.0 中我们有这个

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();

CreateDefaultBuilder(args) 有许多有用的默认值。然而它contains this :

.ConfigureLogging((context, logging) => {
logging.AddConfiguration(context.Configuration.GetSection("Logging"));
logging.AddConsole(); // HERE IS THE PROBLEM
logging.AddDebug(); // HERE IS THE PROBLEM
})

因此控制台和调试日志记录提供程序始终已注册。

我以前是这样注册的

if (env.IsDevelopment())
{
// register them here
}

在生产模式下运行时如何删除/注销它们? 我的意思不是更改日志记录级别,我的意思是我根本不希望它们在生产模式下注册。

最佳答案

我想说设计的方法是通过更改日志记录配置而不向这些提供程序记录任何内容。但我知道您想删除任何生产电话;并且您仍然可以在代码中正确执行此操作。

您可以简单地从传递给 ConfigureLogging lambda 的 HostBuilderContext 访问托管环境:

.ConfigureLogging((context, logging) =>
{
logging.AddConfiguration(context.Configuration.GetSection("Logging"));

if (context.HostingEnvironment.IsDevelopment())
{
logging.AddConsole();
logging.AddDebug();
}
});

显然,仅此一项并不能帮助撤消 CreateDefaultBuilder 调用已经设置的内容。首先,您需要注销这些提供商。为此,您可以使用新的 ILoggingBuilder.ClearProviders方法:

.ConfigureLogging((context, logging) =>
{
// clear all previously registered providers
logging.ClearProviders();

// now register everything you *really* want
// …
});

这是为了响应 this logging issue on GitHub 而引入的.

关于c# - 在生产模式下删除 ASP.NET Core 2.0 中的控制台和调试记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45986517/

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