导入相关库文件:
import logging
import time
import os
import shutil
import re
from logging.handlers import RotatingFileHandler
完整的日志模块:
import logging
import time
import os
import shutil
import re
from logging.handlers import RotatingFileHandler
class Logger(object):
"""
type_name为日志所在文件夹名字, log_content为要保留日志文件夹数量
"""
def __init__(self, type_name, log_content):
self.type_name = type_name
self.log_path, self.path = self.log_start()
self.date_path = os.path.dirname(self.path)
self.all_path = os.path.dirname(self.date_path)
self.log_content = log_content
self.del_log()
"""
path为存放日志的文件夹目录
log_path为日志文件的完整路径
"""
def log_start(self):
loacl_time = time.strftime("%Y_%m_%d", time.localtime())
complete_time = time.strftime("%Y_%m_%d_%H_%M_%S",time.localtime())
path = os.path.join(os.getcwd(), "LOG", loacl_time, self.type_name)
if not os.path.exists(path):
os.makedirs(path)
log_path = os.path.join(path , "%s_"%self.type_name) + complete_time +".log"
file_log = open(log_path, "a")
print(log_path, path)
return log_path, path
"""
设置每份日志最大内存为maxBytes=1024 * 10, 超过该内存自动将日志切割到新日志文件中,
设置backupCount=5,如切割造成新增的日志数量超过五个,自动将五个中旧的日志删除,保留最新的日志并数量保持为五个
"""
def log_main(self, sign, information):
write_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
logger = logging.getLogger('mylogger')
logger.setLevel(level=logging.DEBUG)
fmt = '%(asctime)s - %(levelname)s : %(message)s'
format_str = logging.Formatter(fmt)
fh = RotatingFileHandler(self.log_path, maxBytes=1024 * 10, backupCount=5, encoding="utf-8")
fh.namer = lambda x: self.path + r"\%s_%s_"%(self.type_name, write_time) + x.split(".")[-1] + ".log"
fh.setFormatter(fmt=format_str)
logger.addHandler(fh)
if sign == "debug":
logger.debug(information)
if sign == "info":
logger.info(information)
if sign == "warning":
logger.warning(information)
if sign == "error":
logger.error(information)
if sign == "critical":
logger.critical(information)
logger.removeHandler(fh)
"""
删除超过保留数量的日志文件夹,
例如log_content设置为30,日志文件夹超过30个时就会删除多余的日志文件夹,
让日志文件夹始终保持30个
"""
def del_log(self):
if not os.listdir(self.all_path):
return
print(os.listdir(self.all_path))
date_list = []
for file_name in os.listdir(self.all_path):
if re.fullmatch(r"\d{4}_\d{2}_\d{2}",file_name):
all_name = os.path.join(self.all_path, file_name)
date_list.append(all_name)
print(date_list)
if len(date_list) > self.log_content:
difference_value = len(date_list) - self.log_content
date_list.sort()
for i in range(difference_value):
shutil.rmtree(date_list[i], ignore_errors=True)
if os.path.isfile(date_list[i]):
os.remove(date_list[i])
else:
pass
"""
编写五种报告类型的函数
"""
def Debug(self, information):
sign = "debug"
self.log_main(sign, information)
def Info(self, information):
sign = "info"
self.log_main(sign, information)
def Warning(self, information):
sign = "warning"
self.log_main(sign, information)
def Error(self,information):
sign = "error"
self.log_main(sign, information)
def Critical(self,information):
sign = "critical"
self.log_main(sign, information)
调用方法:
if __name__ == '__main__':
"""
先实例化再进行调用日志模块
"""
logger = Logger("Business",2)
for i in range(240):
logger.Info("zhangsan")
logger.Warning("1111111")
这个日志模块功能很强大,读者可以使用这个日志模块来记录程序的运行过程,本模块编写不容易,望读者给予个大大的赞。
|