"""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", "-"))