-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogging.py
More file actions
37 lines (34 loc) · 1.08 KB
/
logging.py
File metadata and controls
37 lines (34 loc) · 1.08 KB
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
29
30
31
32
33
34
35
36
37
import json
import logging
import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
access_logger = logging.getLogger("access")
class AccessLogMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start = time.time()
model = "-"
if request.method in ("POST", "PUT", "PATCH"):
try:
body = await request.body()
data = json.loads(body)
model = data.get("model", "-")
except Exception:
pass
response = await call_next(request)
duration_ms = (time.time() - start) * 1000
token = request.headers.get("authorization", "")
if token.startswith("Bearer "):
token = f"...{token[-8:]}"
else:
token = "-"
access_logger.info(
"%s %s %s model=%s %d %.0fms",
token,
request.method,
request.url.path,
model,
response.status_code,
duration_ms,
)
return response