123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import os
- import time
- import json
- import logging
- from config import log_root_path
- # 封装logging
- class LogConfig():
- def __init__(self, log_path, logger_name):
- '''
- 指定保存日志的文件路径,日志级别,以及调用文件
- 将日志存入到指定的文件中
- '''
- # 创建logger对象
- self.logger = logging.getLogger(logger_name)
- self.log_path = log_path
- # 设置日志等级
- self.logger.setLevel(logging.INFO) # DEBUG
- # 追加写入文件a ,设置utf-8编码防止中文写入乱码
- fh = logging.FileHandler(self.log_path, mode='a', encoding='utf8', delay=True)
- # 向文件输出的日志级别
- fh.setLevel(logging.INFO)
- # 向文件输出的日志信息格式
- formatter_dict = {
- "sys-msg": "%(asctime)s-%(filename)s-%(lineno)s-%(levelname)s",
- "log-msg": "%(message)s",
- }
- formatter = logging.Formatter(json.dumps(formatter_dict))
- # 将日志信息格式加载到日志文件中
- fh.setFormatter(formatter)
- # 加载文件到logger对象中
- self.logger.addHandler(fh)
-
- # 重置刷新日志
- def log_reset(self):
- # 设置日志定时自动新建
- os.rename(self.log_path, self.log_path.split('.')[0] + '_' + \
- str(time.strftime('%Y_%m%d_%H%M', time.localtime()))+'.log')
-
- # 获取生成日志读写操作并删除多余日志
- def get_log(self):
- self.del_log()
- return self.logger
- # 删除长期未处理日志
- def del_log(self):
- file_list = os.listdir(log_root_path)
- file_path_list = [os.path.join(log_root_path, file) for file in file_list]
- file_path_list = [file_path for file_path in file_path_list
- if self.log_path.split('.')[0] in file_path.split('.')[0]
- and self.log_path != file_path]
- file_path_list = [(file_path, os.path.getctime(file_path))
- for file_path in file_path_list]
- # 根据创建时间排序获取需要删除文件路径名称
- file_sort_list = sorted(file_path_list, key=lambda x: x[1], reverse=True)[1:]
- if len(file_sort_list) > 0:
- for ele in file_sort_list:
- os.remove(ele[0])
|