Add timing middleware to log slow requests (>1s) with [CTRL-TIMING] prefix

This commit is contained in:
YueGuobin 2026-06-15 23:13:36 +08:00
parent a855cb34f1
commit fa9aa5a9cc
No known key found for this signature in database

View File

@ -49,6 +49,7 @@ from gns3server.api.routes import mcp
from gns3server.core import tasks
import logging
import time
log = logging.getLogger(__name__)
@ -214,6 +215,15 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
content={"message": str(exc)}
)
@app.middleware("http")
async def timing_middleware(request: Request, call_next):
_t0 = time.time()
response = await call_next(request)
elapsed = time.time() - _t0
if elapsed > 1.0:
log.info(f"[CTRL-TIMING] request {request.method} {request.url.path} total={elapsed:.3f}s")
return response
# FIXME: do not use this middleware since it creates issue when using StreamingResponse
# see https://starlette-context.readthedocs.io/en/latest/middleware.html#why-are-there-two-middlewares-that-do-the-same-thing