107 lines
4.0 KiB
Python
107 lines
4.0 KiB
Python
# -*- coding: UTF-8 -*-
|
||
"""
|
||
@Project :microproduct
|
||
@File :logHandler.py
|
||
@Function :日志检查、生成
|
||
@Author :SHJ
|
||
@Date :2021/12/1
|
||
@Version :1.0.0
|
||
"""
|
||
import logging
|
||
import os
|
||
import time
|
||
import datetime
|
||
|
||
import colorlog
|
||
|
||
|
||
class LogHandler:
|
||
"""
|
||
生成日志
|
||
"""
|
||
__logger = logging.getLogger("mylog")
|
||
__format_str = logging.Formatter("[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s "
|
||
"(%(filename)s:%(lineno)d) - %(message)s")
|
||
__log_path = None
|
||
|
||
__log_colors_config = {
|
||
'DEBUG': 'blue',
|
||
'INFO': 'cyan',
|
||
'WARNING': 'yellow',
|
||
'ERROR': 'red',
|
||
'CRITICAL': 'red',
|
||
}
|
||
|
||
@staticmethod
|
||
def init_log_handler(log_name):
|
||
"""
|
||
初始化日志
|
||
:param log_name: 日志保存的路径和名称
|
||
:return:
|
||
"""
|
||
path = os.getcwd()
|
||
current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
|
||
LogHandler.__log_path = os.path.join(path, log_name + current_time + ".log")
|
||
para_dir = os.path.split(LogHandler.__log_path)
|
||
if not os.path.exists(para_dir[0]):
|
||
os.makedirs(para_dir[0])
|
||
# 删除七天以前的文件
|
||
LogHandler.delete_outdate_files(para_dir[0])
|
||
|
||
# 方法1:普通日志
|
||
log_format = "[%(asctime)s] [%(process)d] [%(levelname)s]- %(message)s ---from: %(module)s.%(funcName)s" \
|
||
" (%(filename)s:Line%(lineno)d) "
|
||
date_format = "%m/%d/%Y %H:%M:%S"
|
||
formatter = colorlog.ColoredFormatter(
|
||
"%(log_color)s[%(asctime)s] [%(process)d] [%(levelname)s]- %(message)s ---from: %(module)s.%(funcName)s"
|
||
" (%(filename)s:Line%(lineno)d) ",
|
||
log_colors=LogHandler.__log_colors_config)
|
||
fp = logging.FileHandler(LogHandler.__log_path, encoding='utf-8')
|
||
fs = logging.StreamHandler()
|
||
fs.setFormatter(formatter)
|
||
# logging.basicConfig(level=logging.INFO, format=log_format, datefmt=date_format, handlers=[fp, fs]) # 调用
|
||
logging.basicConfig(level=logging.INFO, datefmt=date_format, handlers=[fp, fs]) # 调用
|
||
|
||
# 方法2:回滚日志
|
||
# LogHandler.__logger.setLevel(logging.DEBUG)
|
||
# th = handlers.TimedRotatingFileHandler(filename=LogHandler.__log_path, when='S', interval=1,
|
||
# backupCount=2, encoding='utf-8')
|
||
# th.suffix = "%Y-%m-%d-%H-%M-%S.log"
|
||
# th.setFormatter(LogHandler.__format_str)
|
||
# th.setLevel(level=logging.DEBUG)
|
||
|
||
# console = logging.StreamHandler()
|
||
# console.setLevel(logging.INFO)
|
||
# LogHandler.__logger.addHandler(console)
|
||
# LogHandler.__logger.addHandler(th)
|
||
|
||
@staticmethod
|
||
def delete_outdate_files(path, date_interval=7):
|
||
"""
|
||
删除目录下七天前创建的文件
|
||
"""
|
||
current_time = time.strftime("%Y-%m-%d", time.localtime(time.time()))
|
||
current_time_list = current_time.split("-")
|
||
current_time_day = datetime.datetime(int(current_time_list[0]), int(current_time_list[1]),
|
||
int(current_time_list[2]))
|
||
for root, dirs, files in os.walk(path):
|
||
for item in files:
|
||
item_format = item.split(".", 2)
|
||
if item_format[1] == "log":
|
||
file_path = os.path.join(root, item)
|
||
create_time = time.strftime("%Y-%m-%d", time.localtime((os.stat(file_path)).st_mtime))
|
||
create_time_list = create_time.split("-")
|
||
create_time_day = datetime.datetime(int(create_time_list[0]), int(create_time_list[1]),
|
||
int(create_time_list[2]))
|
||
time_difference = (current_time_day - create_time_day).days
|
||
if time_difference > date_interval:
|
||
os.remove(file_path)
|
||
|
||
#
|
||
# if __name__ == "__main__":
|
||
# # eg2:
|
||
# log_handler = LogHandler()
|
||
# log_handler.init_log_handler(r"run_log\myrun1")
|
||
# logging.warning("1")
|
||
# print("done")
|