Skip to content

Commit 93a91e7

Browse files
committed
use pref_counter() and add uuid
1 parent 5f0cf50 commit 93a91e7

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

gs/backend/api/middleware/logger_middleware.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from collections.abc import Awaitable, Callable, Sequence
22
from datetime import datetime
33
from sys import getsizeof
4-
from time import time
4+
from time import perf_counter
5+
from uuid import uuid4
56

67
from fastapi import FastAPI, Request, Response
78
from loguru import logger
@@ -22,9 +23,9 @@ def __init__(self, app: FastAPI, excluded_endpoints: Sequence[str] = ()) -> None
2223
async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
2324
"""Logs the request and response"""
2425
request_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
25-
start_time = time()
26+
start_time = perf_counter()
2627
response = await call_next(request)
27-
process_time = time() - start_time
28+
process_time = perf_counter() - start_time
2829

2930
if request.url.path in self.excluded_endpoints:
3031
return response
@@ -34,16 +35,18 @@ async def dispatch(self, request: Request, call_next: Callable[[Request], Awaita
3435
# TODO: update this based on userID header name
3536
request_user_id = request.headers.get("user_id", "Anonymous")
3637
request_params = dict(request.query_params)
38+
request_id = str(uuid4())
3739

3840
logger.info(
3941
" | ".join(
4042
[
4143
f"REQUEST | Method: {request.method}",
44+
f"Request ID: {request_id}",
4245
f"URL: {request.url.path}",
4346
f"User id: {request_user_id}",
4447
f"Params: {request_params}",
4548
f"Time: {request_time}",
46-
f"Size: {request_size} bytes.",
49+
f"Bytes: {request_size}.",
4750
]
4851
)
4952
)
@@ -55,6 +58,7 @@ async def dispatch(self, request: Request, call_next: Callable[[Request], Awaita
5558
else:
5659
logger_severity = logger.info
5760

61+
# not all responses have a body_iterator attribute
5862
has_body_iterator = hasattr(response, "body_iterator")
5963

6064
if has_body_iterator:
@@ -69,9 +73,10 @@ async def dispatch(self, request: Request, call_next: Callable[[Request], Awaita
6973
" | ".join(
7074
[
7175
f"RESPONSE | Status: {response.status_code}",
76+
f"Request ID: {request_id}",
7277
f"Response: {response_body}",
73-
f"Size (bytes): {response_size}",
74-
f"Time Elasped: {process_time:.3f} seconds.",
78+
f"Bytes: {response_size}",
79+
f"Seconds Elasped: {process_time:.3f}.",
7580
]
7681
)
7782
)
@@ -83,5 +88,4 @@ async def dispatch(self, request: Request, call_next: Callable[[Request], Awaita
8388
headers=dict(response.headers),
8489
media_type=response.media_type,
8590
)
86-
else:
87-
return response
91+
return response

0 commit comments

Comments
 (0)