-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.py
28 lines (24 loc) · 1.01 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import http
import time
from fastapi import Request
from logger import logger
async def log_request_middleware(request: Request, call_next):
"""
This middleware will log all requests and their processing time.
E.g. log:
0.0.0.0:1234 - GET /ping 200 OK 1.00ms
"""
logger.debug("middleware: log_request_middleware")
url = f"{request.url.path}?{request.query_params}" if request.query_params else request.url.path
start_time = time.time()
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
formatted_process_time = "{0:.2f}".format(process_time)
host = getattr(getattr(request, "client", None), "host", None)
port = getattr(getattr(request, "client", None), "port", None)
try:
status_phrase = http.HTTPStatus(response.status_code).phrase
except ValueError:
status_phrase=""
logger.info(f'{host}:{port} - "{request.method} {url}" {response.status_code} {status_phrase} {formatted_process_time}ms')
return response