-
Notifications
You must be signed in to change notification settings - Fork 75
/
log.py
157 lines (131 loc) · 5.15 KB
/
log.py
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
import logging
import os
import sys
import re
import threading
import time
import inspect
from collections import deque
from html import escape
from loguru import logger
from config import Config
logging.getLogger('werkzeug').setLevel(logging.ERROR)
logging.getLogger('watchdog').setLevel(logging.INFO)
lock = threading.Lock()
LOG_QUEUE = deque(maxlen=200)
LOG_INDEX = 0
class InterceptHandler(logging.Handler):
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 1
while frame.f_code.co_filename == logging.__file__ or frame.f_code.co_filename == __file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
class Logger:
logger = None
__instance = {}
__config = None
def __init__(self, module):
self.logger = logger
self.__config = Config()
logtype = self.__config.get_config('app').get('logtype') or "console"
loglevel = self.__config.get_config('app').get('loglevel') or "info"
handlers = []
self.logger.level(loglevel.upper())
if logtype == "server":
logserver = self.__config.get_config('app').get('logserver', '').split(':')
if logserver:
logip = logserver[0]
if len(logserver) > 1:
logport = int(logserver[1] or '514')
else:
logport = 514
handler = {
"sink": f"tcp://{logip}:{logport}",
"format": "{time:YYYY-MM-DD HH:mm:ss.SSS} |{level:8}| {file} : {module}.{function}:{line:4} | - {message}",
"colorize": False
}
handlers.append(handler)
elif logtype == "file":
# 记录日志到文件
logpath = os.environ.get('NASTOOL_LOG') or self.__config.get_config('app').get('logpath') or ""
if logpath:
if not os.path.exists(logpath):
os.makedirs(logpath)
handler = {
"sink": os.path.join(logpath, module + ".log"),
"rotation": "5 MB",
"format": "{time:YYYY-MM-DD HH:mm:ss.SSS} |{level:8}| {file} : {module}.{function}:{line:4} | - {message}",
"colorize": False,
"retention": "5 days"
}
handlers.append(handler)
# 记录日志到终端
handler = {
"sink": sys.stderr,
"format": "{time:YYYY-MM-DD HH:mm:ss.SSS} |<lvl>{level:8}</>| {file} : {module}.{function}:{line:4} | - <lvl>{message}</>",
"colorize": True
}
handlers.append(handler)
logger.configure(handlers=handlers)
logging.basicConfig(handlers=[InterceptHandler()], level=0)
@staticmethod
def get_instance(module):
if not module:
module = "run"
if Logger.__instance.get(module):
return Logger.__instance.get(module)
with lock:
Logger.__instance[module] = Logger(module)
return Logger.__instance.get(module)
def __append_log_queue(level, text):
global LOG_INDEX, LOG_QUEUE
with lock:
text = escape(text)
if text.startswith("【"):
source = re.findall(r"(?<=【).*?(?=】)", text)[0]
text = text.replace(f"【{source}】", "")
else:
source = "System"
LOG_QUEUE.append({
"time": time.strftime('%H:%M:%S', time.localtime(time.time())),
"level": level,
"source": source,
"text": text})
LOG_INDEX += 1
def debug(text, module=None):
frame, depth = inspect.currentframe(), 0
while frame and (depth == 0 or frame.f_code.co_filename == __file__):
frame = frame.f_back
depth += 1
return Logger.get_instance(module).logger.opt(depth=depth).debug(text)
def info(text, module=None):
frame, depth = inspect.currentframe(), 0
while frame and (depth == 0 or frame.f_code.co_filename == __file__):
frame = frame.f_back
depth += 1
__append_log_queue("INFO", text)
return Logger.get_instance(module).logger.opt(depth=depth).info(text)
def error(text, module=None):
frame, depth = inspect.currentframe(), 0
while frame and (depth == 0 or frame.f_code.co_filename == __file__):
frame = frame.f_back
depth += 1
__append_log_queue("ERROR", text)
return Logger.get_instance(module).logger.opt(depth=depth).error(text)
def warn(text, module=None):
frame, depth = inspect.currentframe(), 0
while frame and (depth == 0 or frame.f_code.co_filename == __file__):
frame = frame.f_back
depth += 1
__append_log_queue("WARN", text)
return Logger.get_instance(module).logger.opt(depth=depth).warning(text)
def console(text):
__append_log_queue("INFO", text)
print(text)