SIMOrthoProgram-Orth_LT1AB-.../Ortho/tool/algorithm/algtools/logHandler.py

91 lines
3.5 KiB
Python
Raw Normal View History

# -*- 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
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
@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"
fp = logging.FileHandler(LogHandler.__log_path, encoding='utf-8')
fs = logging.StreamHandler()
logging.basicConfig(level=logging.INFO, format=log_format, 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")