From 3271e2d563eb1636e3e6d602f19366c9df528f1c Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 27 Nov 2026 09:46:56 +0100 Subject: [PATCH] Log one line per request with the visitor's address Uvicorn's access log named only the proxy (172.17.0.1), with no time taken or client. Each request is now one line: the visitor's address from route-proxy's X-Forwarded-For, the request, status, size, duration, referrer and user agent; uvicorn's own access log is off. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh --- access_log.py | 33 +++++++++++++++++++++++++++++++++ service/Dockerfile | 4 ++-- 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 access_log.py diff --git a/access_log.py b/access_log.py new file mode 100644 index 0000000..f7320d7 --- /dev/null +++ b/access_log.py @@ -0,0 +1,33 @@ +"""One line per request to see the traffic coming in: who asked, what, how it went and how long it took. + +Read it with the container's log (on the mesh: `/docker.docker_logs` for the container f1-circuits). +""" +import logging +import time + +from fastapi import Request + +logger = logging.getLogger("access") + + +def client_address(request: Request) -> str: + """The visitor's address. route-proxy sets X-Forwarded-For; the peer itself is the proxy.""" + forwarded = request.headers.get("x-forwarded-for") + if forwarded: + return forwarded.split(",")[0].strip() + return request.client.host if request.client else "-" + + +async def log_request(request: Request, call_next): + started = time.perf_counter() + status, size = 500, "-" + try: + response = await call_next(request) + status, size = response.status_code, response.headers.get("content-length", "-") + return response + finally: + target = request.url.path + (f"?{request.url.query}" if request.url.query else "") + logger.info('%s "%s %s" %s %sB %.0fms "%s" "%s"', + client_address(request), request.method, target, status, size, + (time.perf_counter() - started) * 1000, + request.headers.get("referer", "-"), request.headers.get("user-agent", "-")) diff --git a/service/Dockerfile b/service/Dockerfile index 385eb00..3c6217e 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -22,10 +22,10 @@ RUN apk add --no-cache \ COPY service/requirements.txt ./requirements.txt RUN pip install --no-cache-dir -r requirements.txt -COPY cdn-api.py circuits_service.py ergast_service.py posters_service.py ./ +COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./ COPY models/ ./models/ COPY circuits/ ./circuits/ EXPOSE 8000 -CMD ["uvicorn", "cdn-api:app", "--host", "0.0.0.0", "--port", "8000"] +CMD ["uvicorn", "cdn-api:app", "--host", "0.0.0.0", "--port", "8000", "--no-access-log"]