mirror of
https://github.com/nihilvux/bancho.py.git
synced 2025-09-16 18:48:38 -07:00
Add files via upload
This commit is contained in:
37
app/api/middlewares.py
Normal file
37
app/api/middlewares.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.base import RequestResponseEndpoint
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.logging import Ansi
|
||||
from app.logging import log
|
||||
from app.logging import magnitude_fmt_time
|
||||
|
||||
|
||||
class MetricsMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(
|
||||
self,
|
||||
request: Request,
|
||||
call_next: RequestResponseEndpoint,
|
||||
) -> Response:
|
||||
start_time = time.perf_counter_ns()
|
||||
response = await call_next(request)
|
||||
end_time = time.perf_counter_ns()
|
||||
|
||||
time_elapsed = end_time - start_time
|
||||
|
||||
col = Ansi.LGREEN if response.status_code < 400 else Ansi.LRED
|
||||
|
||||
url = f"{request.headers['host']}{request['path']}"
|
||||
|
||||
log(
|
||||
f"[{request.method}] {response.status_code} {url}{Ansi.RESET!r} | {Ansi.LBLUE!r}Request took: {magnitude_fmt_time(time_elapsed)}",
|
||||
col,
|
||||
)
|
||||
|
||||
response.headers["process-time"] = str(round(time_elapsed) / 1e6)
|
||||
return response
|
Reference in New Issue
Block a user