logging.py
5.96 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""云端日志:控制台 + data/logs/<年-月>/server_<日期>.log(JSON 行,按天一个文件,保留天数跟随系统设置,默认 180 天)。
敏感串(JWT、令牌)自动打码。Windows 下客户端断开引起的 asyncio 连接重置堆栈不记录(纯噪声)。
"""
from __future__ import annotations
import datetime as dt
import json
import logging
import re
import sys
import threading
from pathlib import Path
from typing import Callable
from .config import C
_JWT = re.compile(r"eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}")
_TOKEN = re.compile(r"edg_[\w-]{16,}")
_WEBHOOK_KEY = re.compile(r"(webhook/send\?key=)[\w-]+")
_DATED = re.compile(r"_(\d{4}-\d{2}-\d{2})(?:_\d+)?\.(log|jsonl)$")
def scrub(s: str) -> str:
return _WEBHOOK_KEY.sub(r"\1***", _TOKEN.sub("edg_***", _JWT.sub("<jwt>", s)))
class JsonFormatter(logging.Formatter):
def format(self, r: logging.LogRecord) -> str:
d = {"ts": self.formatTime(r, "%Y-%m-%d %H:%M:%S"), "level": r.levelname, "logger": r.name,
"msg": scrub(r.getMessage())}
for k in ("store_id", "source", "ref"):
if getattr(r, k, None) is not None:
d[k] = getattr(r, k)
if r.exc_info:
d["exc"] = scrub(self.formatException(r.exc_info))
return json.dumps(d, ensure_ascii=False)
class ConsoleFormatter(logging.Formatter):
def format(self, r: logging.LogRecord) -> str:
return scrub(super().format(r))
class DailyFileHandler(logging.Handler):
"""按天写文件:<root>/<YYYY-MM>/<prefix>_<YYYY-MM-DD>.log;单个文件超过 max_bytes 续写 _2、_3 …
不做改名滚动(多个进程同时写也安全);每天第一次写入时删除超过保留天数的文件和空的月目录。"""
def __init__(self, root: Path, prefix: str, keep_days: Callable[[], int] | int = 180,
max_bytes: int = 50 * 1024 * 1024, ext: str = "log") -> None:
super().__init__()
self.root, self.prefix, self.ext, self.max_bytes = Path(root), prefix, ext, max_bytes
self._keep = keep_days
self._day: dt.date | None = None
self._fh = None
self._path: Path | None = None
self._lock2 = threading.Lock()
def keep_days(self) -> int:
try:
return max(1, int(self._keep() if callable(self._keep) else self._keep))
except Exception: # noqa: BLE001
return 180
def path_for(self, day: dt.date, part: int = 1) -> Path:
suffix = f"_{part}" if part > 1 else ""
return self.root / f"{day:%Y-%m}" / f"{self.prefix}_{day:%Y-%m-%d}{suffix}.{self.ext}"
def _open(self, day: dt.date) -> None:
if self._fh:
self._fh.close()
part = 1
while True:
p = self.path_for(day, part)
if not p.exists() or p.stat().st_size < self.max_bytes:
break
part += 1
p.parent.mkdir(parents=True, exist_ok=True)
self._fh, self._path, self._day = open(p, "a", encoding="utf-8"), p, day
def emit(self, record: logging.LogRecord) -> None:
try:
line = self.format(record)
with self._lock2:
day = dt.date.today()
if day != self._day or self._fh is None:
new_day = day != self._day
self._open(day)
if new_day:
cleanup_dated(self.root, self.prefix, self.keep_days())
elif self._path and self._fh.tell() >= self.max_bytes:
self._open(day)
self._fh.write(line + "\n")
self._fh.flush()
except Exception: # noqa: BLE001
self.handleError(record)
def close(self) -> None:
with self._lock2:
if self._fh:
self._fh.close()
self._fh = None
super().close()
def cleanup_dated(root: Path, prefix: str, keep_days: int) -> int:
"""删除 root 下 <prefix>_<日期>*.log 中早于 keep_days 天的文件,以及空的月目录。"""
cut = dt.date.today() - dt.timedelta(days=keep_days)
n = 0
if not root.exists():
return 0
for month in root.iterdir():
if not month.is_dir() or not re.fullmatch(r"\d{4}-\d{2}", month.name):
continue
for f in month.iterdir():
m = _DATED.search(f.name)
if f.name.startswith(prefix + "_") and m and dt.date.fromisoformat(m.group(1)) < cut:
try:
f.unlink()
n += 1
except OSError:
pass
try:
next(month.iterdir())
except StopIteration:
month.rmdir()
except OSError:
pass
return n
class _NoiseFilter(logging.Filter):
"""Windows Proactor 事件循环在客户端断开(WinError 10054)时打印整段堆栈,没有任何信息量。"""
def filter(self, r: logging.LogRecord) -> bool:
if r.name == "asyncio":
exc = r.exc_info[1] if r.exc_info else None
if isinstance(exc, (ConnectionResetError, ConnectionAbortedError)) or "_call_connection_lost" in str(r.msg):
return False
return True
def _retention() -> int:
from ..services import settings
return settings.get().edge_log_retention_days
_done = False
def setup(level: str = "INFO") -> None:
global _done
if _done:
return
_done = True
root = logging.getLogger()
root.setLevel(level)
noise = _NoiseFilter()
con = logging.StreamHandler(sys.stdout)
con.setFormatter(ConsoleFormatter("%(asctime)s %(levelname)s [%(name)s] %(message)s", "%H:%M:%S"))
con.addFilter(noise)
root.addHandler(con)
fh = DailyFileHandler(C.data_dir / "logs", "server", _retention)
fh.setFormatter(JsonFormatter())
fh.addFilter(noise)
root.addHandler(fh)
for noisy in ("httpx", "httpx2", "httpcore", "openai", "urllib3", "uvicorn.access", "alembic"):
logging.getLogger(noisy).setLevel(logging.WARNING)