Python FastAPI 健康检查日志

pyh*_*hot 11 python amazon-web-services amazon-ecs python-3.7 fastapi

我最近使用 FastAPI 框架创建了一个 python API,并使其在我的 AWS ECS 服务中运行良好。我已经设置了 /health 端点以供 ALB 进行运行状况检查。我的 ECS 容器的入口点是这个命令

ENTRYPOINT ["app/start.sh"]
Run Code Online (Sandbox Code Playgroud)

这就是我的 start.sh 中的内容

uvicorn main:app --host 0.0.0.0
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当 ALB 命中 /health 端点时,我的 ECS 日志中充满了 200 OK。非常令人沮丧的是,我几乎找不到我的 API 日志,而 Cloudwatch 中充满了 /health 端点日志。有没有办法可以避免健康端点日志?

在此输入图像描述

@app.get("/health", response_class=PlainTextResponse)
def healthcheck():
    return "200"
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 17

此 github 问题上的评论提供了一个示例,说明如何在 Python 应用程序中使用 uvicorn 时过滤出给定端点的日志。

它解释了您需要为端点定义一个过滤器,并将其添加到记录器中。正如MatsLindh 在下面的评论中提到的,上面的方法会过滤掉/health日志消息中出现的任何情况 - 这意味着它也会过滤掉诸如/foo/health/foo/health/bar端点。

上述示例的修改示例,用于过滤/health端点的访问日志:

import logging
import uvicorn
from fastapi import FastAPI

app = FastAPI()

# Define the filter
class EndpointFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        return record.args and len(record.args) >= 3 and record.args[2] != "/health"

# Add filter to the logger
logging.getLogger("uvicorn.access").addFilter(EndpointFilter())

# Define the API endpoints
@app.get('/health')
def health():
    print('health endpoint')

@app.get('/test')
def test():
    print('test endpoint')
Run Code Online (Sandbox Code Playgroud)

点击/test端点,我们可以看到有一个访问日志和函数的输出。端点没有访问日志/health,只有函数的输出。

INFO:     Started server process [11272]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
test endpoint
INFO:     127.0.0.1:54014 - "GET /test HTTP/1.1" 200 OK
health endpoint
Run Code Online (Sandbox Code Playgroud)