.net 核心日志过滤某些请求 [英] .net core log filtering on certain requests

查看:25
本文介绍了.net 核心日志过滤某些请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的生产环境中,我们有一个负载平衡的 .net 核心 Web 服务,因此负载平衡器每秒调用一个特殊的/health URL 来检查服务是否仍在运行.当 loglevel 设置为 Info 时,由于这些重复调用,日志文件很快就会被填满.看到有问题的日志来自 .net 核心框架,我不知道如何在不过滤掉所有请求的情况下过滤掉这些请求.此类请求的日志示例为:

In our production environment we have a .net core web service which is load balanced and as a result the load balancer calls a special /health URL every second to check that the service is still up. When the loglevel is set to Info, the log file is quickly filled due to these repeated calls. Seeing as the logs in question come from the .net core framework I can't see how I could filter out these requests without filtering out all requests. Example of the log for this type of request is:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5555/Health
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 1674.6082ms 200

知道如何在不过滤掉所有其他请求的情况下过滤掉这些请求吗?

Any idea how we could filter these out without also filtering out all other requests ?

推荐答案

我设法使用依赖注入来覆盖默认的 ILoggerProvider 一个可以注入我自己的自定义 ILogger> 仅适用于 Microsoft.AspNetCore.Hosting.Diagnostics 类别并跳过记录来自我的健康检查端点的任何事件.这可以过滤掉请求开始"事件,但请求完成"事件使用一个对象,该对象将请求的路径隐藏在私有字段中.我在使用反射检查请求的路径时画了一条线,结果是这样的:

I managed to use dependency injection to overwrite the default ILoggerProvider with one that could inject my own custom ILogger for only the Microsoft.AspNetCore.Hosting.Diagnostics category and skip logging any events that came from my health check endpoint. This works to filter out the 'Request started' event but the 'Request finished' event uses an object that hides the path of the request in a private field. I drew the line at using reflection to check the path of the request and ended up with this:

app.Use(async (context, next) =>
{
    if (context.Request.Path != "/api/v1/liveness")
    {
        Console.WriteLine($"info: Microsoft.AspNetCore.Hosting.Diagnostics[1]");
        Console.WriteLine($"      Request starting {context.Request.Protocol} {context.Request.Method} {context.Request.Scheme}://{context.Request.Host}{context.Request.Path} {context.Request.ContentLength ?? 0}");
        var sw = Stopwatch.StartNew();
        await next.Invoke();
        Console.WriteLine($"info: Microsoft.AspNetCore.Hosting.Diagnostics[2]");
        Console.WriteLine($"      Request finished in {sw.Elapsed.TotalMilliseconds}ms {context.Response.StatusCode}");
    }
    else
    {
        // liveness probe logic
    }
})

它完成了工作,因为在我的 appsettings.json 中,我已将该类别的日志级别设置为警告:

It gets the job done because in my appsettings.json I've set the log level for that category to warning:

"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore.Hosting.Diagnostics": "Warning"
  }
}

这篇关于.net 核心日志过滤某些请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆