logs.py
1.54 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
# -*- coding: utf-8 -*-
"""日志:控制台 + 按天滚动文件 logs/edge.log;统一脱敏(复用 dmsfetch.logutil 的 scrub)。
另外维护一个内存缓冲(最近 N 行),连接云端时随任务结果一起回传,方便在云端页面看现场日志。
"""
import collections
import logging
import logging.handlers
import os
import threading
from .dmsfetch.logutil import _ScrubFormatter, scrub
_BUF = collections.deque(maxlen=400)
_LOCK = threading.Lock()
class _BufHandler(logging.Handler):
def emit(self, record):
try:
line = self.format(record)
except Exception:
return
with _LOCK:
_BUF.append(line)
def drain():
"""取出并清空缓冲的日志行(回传云端用)。"""
with _LOCK:
lines = list(_BUF)
_BUF.clear()
return lines
def setup(log_dir, level="INFO"):
fmt = _ScrubFormatter("%(asctime)s [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S")
os.makedirs(log_dir, exist_ok=True)
fh = logging.handlers.TimedRotatingFileHandler(
os.path.join(log_dir, "edge.log"), when="midnight", backupCount=30, encoding="utf-8")
fh.setFormatter(fmt)
ch = logging.StreamHandler()
ch.setFormatter(fmt)
bh = _BufHandler()
bh.setFormatter(fmt)
for name in ("edge", "dmsfetch"):
lg = logging.getLogger(name)
lg.setLevel(getattr(logging, level, logging.INFO))
lg.handlers = [ch, fh, bh]
lg.propagate = False
return logging.getLogger("edge")
__all__ = ["setup", "drain", "scrub"]