This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathlog.py
127 lines (115 loc) · 4.39 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
import logging
import re
from datetime import datetime
from sys import stdout
import colorlog
import os
from logging.handlers import RotatingFileHandler
from conn.Web.ws_send import send_message
from conn.tools.conn import ConnYml
yml = ConnYml()
yml.creat_yml()
read = yml.read_yaml()
class LoggerClass:
logFile = read['log'] # 定义日志存储的文件夹
log_colors_config = {
'DEBUG': 'cyan',
'INFO': 'purple',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
def __init__(self, level='info'):
self.level = level
self.norm_fomatter = colorlog.ColoredFormatter(f'%(log_color)s[%(asctime)s]\t'
'%(message)s',
log_colors=self.log_colors_config)
# 提取路径
pa = re.findall('(.*?)/\w+\.log', self.logFile)
if pa:
if not os.path.exists(pa[0]): # 判断日志存储文件夹是否存在,不存在,则新建
os.makedirs(pa[0])
# 初始化日志类参数
self.logger = logging.getLogger(__name__)
# self.logger.setLevel(self.level_relations.get(level))
self.logger.setLevel('DEBUG')
# 生成以当天日期为名称的日志文件
self.filename = self.logFile
# 定义日志输出到前面定义的filename中
self.filelogger = RotatingFileHandler(self.logFile, 'a+', encoding="UTF-8")
self.filelogger.setLevel('DEBUG') # 设置Handler级别
# self.filelogger.setLevel(self.level_relations.get(level))
# 定义日志输出的格式
# formatter = logging.Formatter(fmt)
# asctime可能用不了
self.filelogger.setFormatter(self.norm_fomatter)
# 控制台
self.norm_hdl_std = logging.StreamHandler(stdout)
self.norm_hdl_std.setLevel('DEBUG') # 设置Handler级别
self.norm_hdl_std.setFormatter(self.norm_fomatter)
if not self.logger.handlers:
self.logger.addHandler(self.norm_hdl_std)
self.logger.addHandler(self.filelogger)
def write_log(self, message, level=""):
"""
#日志输出到控制台
console=logging.StreamHandler()
self.logger.addHandler(console)
"""
lev = level if level else self.level
msg_format = f'[{lev}]-\t{message}'
try:
if lev == 'debug':
self.logger.debug(msg=msg_format)
send_message(f"{self.TimeStampToTime()}\t{msg_format}")
elif lev == 'info':
self.logger.info(msg=msg_format)
send_message(f"{self.TimeStampToTime()}\t{msg_format}")
elif lev == 'warning':
self.logger.warning(msg=msg_format)
send_message(f"{self.TimeStampToTime()}\t{msg_format}")
elif lev == 'error':
self.logger.error(msg=msg_format)
send_message(f"{self.TimeStampToTime()}\t{msg_format}")
else:
self.logger.critical(msg=msg_format)
send_message(f"{self.TimeStampToTime()}\t{msg_format}")
except Exception as e:
print("日志写入权限错误:", e)
def TimeStampToTime(self):
"""
伪造日志时间
:return:
"""
return str("[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S,%f]')[:-4] + "]")
def read_log(self):
"""
读取日志文件
:return: 打印html格式的日志,异常返回-1
"""
try:
st = []
rz1 = yml.read_txt(self.logFile)
if rz1 == -1:
return []
if len(rz1) > 100:
yml.delete_first_lines(self.logFile, -100)
sun = 0
# 颠倒数组顺序
rz1.reverse()
# 遍历所有行
for i in rz1:
if sun < 100:
sun += 1
else:
break
# 如果就\n则跳过
if i == '\n':
continue
j = re.sub("(?:\[35m|\[0m|\[33m|\[36m|\[31m|\n)", '', i)
st.append(j)
# 把颠倒的顺序颠倒回来
st.reverse()
return st
except Exception as e:
return [f'com.gheaders.log. LoggerClass.read_log 日志文件异常: {e}']