pyhotshot
pyhotshot

Reputation: 515

Python FastAPI health check logs

I have recently created a python API using the FastAPI framework and got it running fine in my AWS ECS Service. I have set up a /health endpoint for health checks by ALB. The Entrypoint for my ECS container is this command

ENTRYPOINT ["app/start.sh"]

and this is what I have in my start.sh

uvicorn main:app --host 0.0.0.0

The problem I have is that my ECS logs are filled with 200 OKs when ALB hits /health endpoint. It is very frustrating that I can hardly find my API logs and Cloudwatch is filled with /health endpoint logs. Is there a way that I can avoid health endpoint logs?

enter image description here

@app.get("/health", response_class=PlainTextResponse)
def healthcheck():
    return "200"

Upvotes: 14

Views: 18468

Answers (1)

Josh
Josh

Reputation: 1976

The comment on this github issue provides an example of how to filter out the logs for a given endpoint when using uvicorn, from within your Python app.

It explains that you need to define a filter for the endpoint, and add it to the logger. As MatsLindh mentioned in the comments below, the method above filters out any occurance of /health in the log messages - meaning it would also filter out endpoints such as /foo/health, /foo/health/bar etc.

A modified example of the above that filters out the access logs for the /health endpoint:

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')

Hitting the /test endpoint, we can see there is an access log and the output of the function. There is no access log for the /health endpoint, only the output of the function.

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

Upvotes: 24

Related Questions