通过 MVC 禁用类似跟踪的 INFO 日志记录

Disabling trace-like INFO logging by MVC

为 ASP.NET 核心 MVC 应用程序启用应用程序日志记录时,我发现针对向 API 发出的每个请求记录了很多低级详细信息(请参见下面的示例).

我发现这会用类似跟踪的详细信息污染应用程序日志(尤其是因为我们每分钟收到数百个请求),因此很难处理。

有什么方法可以禁用它吗?或者我应该看看另一种记录方法?

API 请求的信息日志示例

2017-03-14 09:23:46.944 +00:00 [Information] Request starting HTTP/1.1 GET http://example.net/api/something application/json

2017-03-14 09:23:46.944 +00:00 [Information] Successfully validated the token.

2017-03-14 09:23:46.944 +00:00 [Information] HttpContext.User merged via AutomaticAuthentication from authenticationScheme: "Bearer".

2017-03-14 09:23:46.944 +00:00 [Information] AuthenticationScheme: "Bearer" was successfully authenticated.

2017-03-14 09:23:46.944 +00:00 [Information] Authorization was successful for user: null.

2017-03-14 09:23:46.944 +00:00 [Information] Executing action method "Xyz.GetAsync (Xyz.Api)" with arguments (["Xyz.Something", "", "", "", "", "0", "100", "", "2017-06-01T00:00:00Z", "False"]) - ModelState is Valid

2017-03-14 09:23:47.115 +00:00 [Information] Executing JsonResult, writing value "Xyz.Resources.SomeModel[]".

2017-03-14 09:23:47.115 +00:00 [Information] Executed action "Xyz.GetAsync (Xyz.Api)" in 206.5169ms

2017-03-14 09:23:47.115 +00:00 [Information] Request finished in 216.8241ms 200 application/json; charset=utf-8

日志级别

这些似乎都是 Information,您应该可以在 appsettings.json 中进行调整,使记录的条目级别大于 "info"...参见 Log Level

记录事件 ID

日志级别是应用程序范围的,因此在这方面使用日志记录的所有事物都是平等的。如果您希望您的日志脱颖而出并发现它们更重要,请将它们原封不动地记录下来。将它们记录为警告 - 如果合适的话。此外,作为替代方案,您可以使用 EventId 开始隔离日志。这个想法是您可以根据 "id" 过滤日志以快速找到感兴趣的东西。

过滤器

最后,您可以应用过滤器了。

You can set filtering rules for all providers that are registered with an ILoggerFactory instance by using the WithFilter extension method. The example below limits framework logs (category begins with "Microsoft" or "System") to warnings while letting the app log at debug level.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .WithFilter(new FilterLoggerSettings
        {
            { "Microsoft", LogLevel.Warning },
            { "System", LogLevel.Warning },
            { "ToDoApi", LogLevel.Debug }
        })
        .AddConsole()
        .AddDebug()
}

我认为过滤器正是您在这里寻找的。指定 MicrosoftSystem 都在 LogLevel.Warning,那么你应该只看到它们的重要日志。

看起来这个钩子在 netcoreapp2.0 中略有变化:

public virtual void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ILoggerFactory, LoggerFactory>();
    services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
    services.AddLogging(builder =>
    {
        builder.SetMinimumLevel(LogLevel.Trace);
        builder.AddFilter("Microsoft", LogLevel.Warning);
        builder.AddFilter("System", LogLevel.Error);
        builder.AddFilter("Engine", LogLevel.Debug);
    });

    /// ... etc
}

添加上面的内容对我有用。