Drop-in ASGI/WSGI middleware for endpoint timing
pip install philiprehberger-api-timer
Drop-in ASGI/WSGI middleware for endpoint timing with Server-Timing headers.
pip install philiprehberger-api-timer
from fastapi import FastAPI
from philiprehberger_api_timer import ASGITimerMiddleware
app = FastAPI()
app.add_middleware(ASGITimerMiddleware, slow_threshold_ms=500)
from flask import Flask
from philiprehberger_api_timer import WSGITimerMiddleware
app = Flask(__name__)
app.wsgi_app = WSGITimerMiddleware(app.wsgi_app, slow_threshold_ms=500)
import logging
from philiprehberger_api_timer import ASGITimerMiddleware
logger = logging.getLogger("my_api")
app.add_middleware(ASGITimerMiddleware, logger=logger, include_header=False)
from philiprehberger_api_timer import ASGITimerMiddleware
app.add_middleware(
ASGITimerMiddleware,
exclude_paths=["/health", "/metrics"], # bypass timing entirely
)
from philiprehberger_api_timer import WSGITimerMiddleware
app.wsgi_app = WSGITimerMiddleware(app.wsgi_app, header_name="X-Request-Time")
metric_callbackfrom philiprehberger_api_timer import ASGITimerMiddleware
def record(method: str, path: str, status: int, elapsed_ms: float) -> None:
histogram.labels(method=method, path=path, status=status).observe(elapsed_ms)
app.add_middleware(ASGITimerMiddleware, metric_callback=record)
The callback fires once per non-excluded request after the response has been sent. Exceptions raised inside the callback are caught and logged so they cannot break the response.
Server-Timing header to every response (e.g., Server-Timing: total;dur=42.5)| Function / Class | Description |
|---|---|
ASGITimerMiddleware(app, logger=None, slow_threshold_ms=500, include_header=True, header_name="Server-Timing", exclude_paths=None, metric_callback=None) | ASGI middleware |
WSGITimerMiddleware(app, logger=None, slow_threshold_ms=500, include_header=True, header_name="Server-Timing", exclude_paths=None, metric_callback=None) | WSGI middleware |
MetricCallback | Type alias for (method, path, status, elapsed_ms) -> None |
pip install -e .
python -m pytest tests/ -v
If you find this project useful: