logging 滚动打印日志
程序员文章站
2022-07-15 15:46:05
...
滚动打印日志
有空再补充,先贴代码。
# coding:utf-8
import logging
import time
import re
from logging.handlers import TimedRotatingFileHandler
import os
def deleteDuplicatedElementFromList(listA):
return sorted(set(listA), key = listA.index)
def deleteDuplicatedHandler(listA):
listB = []
i = 0
while(i < len(listA)):
if str(listA[i]) in listB:
del listA[i]
else:
listB.append(str(listA[i]))
i += 1
return listA
def initbackroll():
log = logging.getLogger()
log_fmt = '%(asctime)s \"%(filename)s\" [line:%(lineno)d] %(levelname)s: %(message)s'
formatter = logging.Formatter(log_fmt)
logging.basicConfig(level=logging.INFO)
log_path = os.path.dirname(os.path.abspath(__file__)) + '\\Logs\\'
if not os.path.exists(log_path):
os.mkdir(log_path)
file_handler = TimedRotatingFileHandler(filename=log_path + "logupdate",
when="H", interval=6, backupCount=12)
file_handler.suffix = "%Y-%m-%d_%H.log"
file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}.log$")
file_handler.setFormatter(formatter)
file_handler.setLevel(level=logging.INFO)
console = logging.StreamHandler()
console.setLevel(level=logging.INFO)
console.setFormatter(formatter)
log.addHandler(file_handler)
log.addHandler(console)
del log.handlers[0]
deleteDuplicatedHandler(log.handlers)
return log
# log.removeHandler(file_handler)
if __name__ == "__main__":
pass
'''**********************************************************************
interval: 滚动周期,单位有when指定,比如:when=’D’,interval=1,表示每天产生一个日志文件;
backupCount: 表示日志文件的保留个数;
注意TimedRotatingFileHandler这个函数里的when和文件名的正则表达式需要匹配,否则会出现过期删除出错的情况!
'S':suffix="%Y-%m-%d_%H-%M-%S",extMatch=r"\^d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}";
'M':suffix="%Y-%m-%d_%H-%M",extMatch=r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}";
'H':suffix="%Y-%m-%d_%H",extMatch=r"^\d{4}-\d{2}-\d{2}_\d{2}";
'D':suffxi="%Y-%m-%d",extMatch=r"^\d{4}-\d{2}-\d{2}";
'MIDNIGHT':"%Y-%m-%d",extMatch=r"^\d{4}-\d{2}-\d{2}";
'W':"%Y-%m-%d",extMatch=r"^\d{4}-\d{2}-\d{2}";
**********************************************************************'''
上一篇: logging
下一篇: Python Logging模块学习笔记