-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathlog.py
More file actions
74 lines (57 loc) · 2 KB
/
Copy pathlog.py
File metadata and controls
74 lines (57 loc) · 2 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
import inspect
import logging
import sys
from typing import TYPE_CHECKING, Any
import loguru
if TYPE_CHECKING:
from loguru import Logger
logger: "Logger" = loguru.logger.bind(name="Main")
def formatter(record: Any) -> str:
record["extra"].setdefault("name", "UNNAMED")
rid = record["extra"].get("req_id")
if rid:
return (
"<green>{time:HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{name}:{function}:{line}</cyan> | "
"<level>[{extra[name]}][{extra[req_id]}] {message}</level>\n"
"{exception}"
)
else:
return (
"<green>{time:HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{name}:{function}:{line}</cyan> | "
"<level>[{extra[name]}] {message}</level>\n"
"{exception}"
)
def setup_logging(debug: bool = False) -> None:
logger.remove()
level = "DEBUG" if debug else "INFO"
logger.add(sys.stderr, level=level, format=formatter)
logger.add(
"logs/bot.log",
rotation="10 MB",
level="INFO",
format=formatter,
enqueue=True,
)
if debug:
logger.debug("调试模式已启用")
class InterceptHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
try:
level: str | int = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = inspect.currentframe(), 0
while frame:
filename = frame.f_code.co_filename
is_logging = filename == logging.__file__
is_frozen = "importlib" in filename and "_bootstrap" in filename
if depth > 0 and not (is_logging or is_frozen):
break
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
logging.basicConfig(handlers=[InterceptHandler()], level="ERROR", force=True)