request_log.py
2.51 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""接口请求日志:写操作(非 GET)和所有 4xx / 5xx 各记一行(谁、从哪个 IP、调了什么、结果),排查「这个动作是谁做的」用。
uvicorn 自带的访问日志是关着的(轮询太多);取数端接口(/api/edge/)心跳频繁,也不记。
不记查询串和请求体(可能带登录令牌、密码);路径里的长令牌(单据令牌)只留前 6 位。
来源 IP 经过反向代理时由 uvicorn 按 X-Forwarded-For 改写(可以伪造),所以把这个头的原文也写上;要最准的来源 IP 看 nginx。
"""
from __future__ import annotations
import logging
import re
import time
log = logging.getLogger("server.request")
SKIP = ("/api/edge/",)
_LONG = re.compile(r"(?<=/)([\w-]{6})[\w-]{10,}(?=/|$)")
def mask_path(path: str) -> str:
return _LONG.sub(r"\1…", path)
def _clean(v: str, n: int) -> str:
"""请求头由客户端控制:去掉控制字符(防止伪造日志行)并截断。"""
return re.sub(r"[\x00-\x1f\x7f]+", " ", v)[:n]
def _header(headers, name: bytes) -> str:
for k, v in headers or []:
if k.lower() == name:
return v.decode("latin-1")
return ""
class RequestLog:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http" or not scope["path"].startswith("/api/") or scope["path"].startswith(SKIP):
return await self.app(scope, receive, send)
t0 = time.monotonic()
st = {"status": 0}
async def _send(msg):
if msg["type"] == "http.response.start":
st["status"] = msg["status"]
await send(msg)
try:
await self.app(scope, receive, _send)
finally:
status = st["status"] # 0 = 没来得及响应(抛异常或客户端断开)
bad = status >= 400 or not status
if scope["method"] not in ("GET", "HEAD", "OPTIONS") or bad:
hdrs = scope.get("headers")
log.log(logging.WARNING if bad else logging.INFO,
"%s %s → %s,%.2f 秒,来源 %s,X-Forwarded-For %s,UA %s",
scope["method"], _clean(mask_path(scope["path"]), 200), status or "没有响应", time.monotonic() - t0,
(scope.get("client") or ("?",))[0],
_clean(_header(hdrs, b"x-forwarded-for"), 200) or "-",
_clean(_header(hdrs, b"user-agent"), 120) or "-")