[英]ASP.NET Core logging too verbose
我在ASP.NET Core 2.1 WebApi应用程序中的配置日志记录方面遇到麻烦。 我成功实现了将消息记录到Azure并在日志流中检查消息,但是这些日志太冗长。 我不想将类别为Microsoft.AspNetCore
消息登录到信息级别 。 这是我在appsettings.json
文件中的日志记录部分:
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore.Hosting.Internal.WebHost": "Debug",
"GameHub": "Information"
}
}
和我的Program
类:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true); })
.ConfigureLogging((ctx, logging) =>
{
logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
});
}
它仍然在信息级别而不是调试级别记录来自Microsoft.AspNetCore
类别的消息。
我究竟做错了什么?
信息化水平高于 (或低于,这取决于你怎么看它)调试水平,因此更简洁。 如果将其设置为“调试”,则还将获得所有信息(以及警告,错误)。 我怀疑您可以在标准Core日志记录中更改它。
作为参考,大多数日志框架(从最详细到最不详细)的日志级别为:
详细,调试,信息,警告,错误,致命
(某些框架使用的命名稍有不同,正如Tseng在下面的注释中正确指出的,但基本思想保持不变)。
在某些框架(例如log4net)上,您可以设置最大和最小级别,但是带有Core内置日志记录的AFAIK只能设置最小级别,因此也可以使所有级别都超过该级别。
如Sellotape所说,.NET Core中设置的日志级别是最低级别。
设置Debug
,它将记录Critical, Error, Warning, Information, Debug
级别。 它不会记录Trace
(最高详细程度)。
如果您不希望Information
,请将其设置为Warning
,那么只会记录Critical, Error, Warning
。
但是,如果您想在没有信息的情况下进行Critical, Error, Warning, Debug
,则无法直接使用appsettings.json
来做到这appsettings.json
。
public static class Program
{
public static void Main(string[] args) => CreateWebHostBuilder(args).Build().Run();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) => { ... })
.ConfigureLogging((webhostContext, builder) => {
builder.AddConfiguration(webhostContext.Configuration.GetSection("Logging"))
.AddFilter<ConsoleLoggerProvider>(logLevel => logLevel!=LogLevel.Information)
.AddConsole()
.AddDebug();
})
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights();
}
的
// by strong typedProvider
.AddFilter<ConsoleLoggerProvider>(logLevel => logLevel!=LogLevel.Information)
// or by name
.AddFilter("Console", logLevel => logLevel != LogLevel.Information)
// or generic/global
.AddFilter(logLevel => logLevel != LogLevel.Information)
如ASP.NET Core文档中所示,添加带有三个谓词( Func<string, string, LogLevel, bool>
, Func<string, LogLevel, bool>
, Func<LogLevel, bool>
)之一的日志记录过滤器:
过滤功能
对于没有通过配置或代码为其分配规则的所有提供者和类别,将调用过滤器功能。 函数中的代码可以访问提供程序类型,类别和日志级别。 例如:
WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logBuilder => { logBuilder.AddFilter((provider, category, logLevel) => { if (provider == "Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider" && category == "TodoApiSample.Controllers.TodoController") { return false; } return true; }); }) .Build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.