Python 标准库

logging

2023-01-01
1
import logging
2
from logging.handlers import RotatingFileHandler
3
4
class Log():
5
"""对日志输出功能进行封装"""
6
7
def __init__(self, filename):
8
"""初始化日志格式"""
9
self.filename = filename + ".log"
10
self.LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
11
self.DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
12
13
def log(self):
14
15
# 配置日志超过指定大小删除
16
rfh = RotatingFileHandler(
17
filename=self.filename,
18
maxBytes=1024*1024*5,
19
backupCount=1)
20
# 配置日志格式
21
logging.basicConfig(
22
format=self.LOG_FORMAT,
23
datefmt=self.DATE_FORMAT,
24
level=logging.INFO, # 日志最低严重级别
25
handlers=[rfh]
26
)
27
28
return logging
29
30
if __name__ == "__main__":
31
32
log = Log('test').log()
33
log.debug('TEST, 42')