import time
import logging
from logging.handlers import TimedRotatingFileHandler
class Log:
def __init__(self, name=None, log_level=logging.DEBUG):
# 获取logger对象
self.logger = logging.getLogger(name)
# 指定最低日志级别:(critical > error > warning > info > debug)
self.logger.setLevel(log_level)
# 日志格化字符串
file_fmt = '%(asctime)s-%(threadName)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s'
file_formatter = logging.Formatter(fmt=file_fmt)
# 输出到文件
file_name = f'./logs/test.log'
# 每隔1分钟新建1个日志文件,并保留最新的2个
file_handler = TimedRotatingFileHandler(filename=file_name, when='M', interval=1, backupCount=2,
encoding='utf-8')
# 每隔5秒新建1个日志文件,并保留最新的3个
# file_handler = TimedRotatingFileHandler(filename=file_name, when='S', interval=5, backupCount=3, encoding='utf-8')
# 设置日志格式
file_handler.setFormatter(file_formatter)
# logger添加处理器
# 避免重复打印日志
if not self.logger.handlers:
self.logger.addHandler(file_handler)
def debug(self, message):
self.logger.debug(message)
def info(self, message):
self.logger.info(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
def critical(self, message):
self.logger.critical(message)
if __name__ == '__main__':
log = Log()
for i in range(200):
log.info(f'test_{i}')
time.sleep(1)