Import source: axon/middleware/request_context
Import the existing local project snapshot. This commit organizes existing files; it does not represent newly developed functionality.
This commit is contained in:
@@ -0,0 +1,24 @@
|
|||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
from starlette.requests import Request
|
||||||
|
|
||||||
|
from axon.services.metrics import metrics
|
||||||
|
|
||||||
|
|
||||||
|
class RequestContextMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
|
||||||
|
start = time.monotonic()
|
||||||
|
status_code = 500
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
status_code = response.status_code
|
||||||
|
return response
|
||||||
|
finally:
|
||||||
|
latency_ms = (time.monotonic() - start) * 1000
|
||||||
|
await metrics.record(request.url.path, status_code, latency_ms)
|
||||||
|
if "response" in locals():
|
||||||
|
response.headers["X-Request-ID"] = request_id
|
||||||
Reference in New Issue
Block a user