34 lines
876 B
Python
34 lines
876 B
Python
import uuid
|
|
|
|
import structlog
|
|
from fastapi import Request
|
|
|
|
from .app import app, logger
|
|
|
|
|
|
@app.middleware("http")
|
|
async def logger_middleware(request: Request, call_next):
|
|
structlog.contextvars.clear_contextvars()
|
|
structlog.contextvars.bind_contextvars(
|
|
path=request.url.path,
|
|
method=request.method,
|
|
client_host=request.client.host,
|
|
request_id=str(uuid.uuid4()),
|
|
)
|
|
response = await call_next(request)
|
|
|
|
structlog.contextvars.bind_contextvars(
|
|
status_code=response.status_code,
|
|
)
|
|
|
|
# Exclude /healthcheck endpoint from producing logs
|
|
if request.url.path != "/healthcheck":
|
|
if 400 <= response.status_code < 500:
|
|
logger.warn("Client error")
|
|
elif response.status_code >= 500:
|
|
logger.error("Server error")
|
|
else:
|
|
logger.info("OK")
|
|
|
|
return response
|