功能:
- 自动保存目录logs
- 超过2MB自动新增一个log
- 超过20个log文件则删除
源码:
import os
import sys
import time
import shutil
import datetime
import logging
import configparser
from logging.handlers import RotatingFileHandler
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
cfg_path = os.path.join(base_path, 'config.ini')
cf = configparser.ConfigParser() # 配置文档实例化
cf.read(cfg_path, encoding='utf-8-sig') # 读取配置文档
def get_log_path():
return os.path.join(base_path, 'logs')
def cleanup_logs():
log_path = get_log_path()
current_time = time.time()
for file_name in os.listdir(log_path):
file_path = os.path.join(log_path, file_name)
if os.path.isfile(file_path):
creation_time = os.path.getctime(file_path)
if current_time - creation_time > (3 * 24 * 60 * 60):
os.remove(file_path)
def configure_logging():
log_path = get_log_path()
os.makedirs(log_path, exist_ok=True)
log_filename = get_log_filename()
log_file = os.path.join(log_path, log_filename)
# 创建文件处理器
file_handler = RotatingFileHandler(log_file, maxBytes=2 * 1024 * 1024, backupCount=1)
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# 添加文件处理器到日志记录器
logger.addHandler(file_handler)
return file_handler
def get_log_filename():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d_%H-%M.log")
def create_new_log():
log_path = get_log_path()
log_files = os.listdir(log_path)
if len(log_files) >= 20:
oldest_file = min(log_files)
os.remove(os.path.join(log_path, oldest_file))
log_filename = get_log_filename()
log_filepath = os.path.join(log_path, log_filename)
return log_filepath
def check_log_size(log_filepath):
log_size = os.path.getsize(log_filepath)
if log_size > 2 * 1024 * 1024:
# 创建新的日志文件
new_log_filepath = create_new_log()
try:
shutil.move(log_filepath, new_log_filepath)
return new_log_filepath
except PermissionError:
insert_log(logger, f'{log_filepath} {PermissionError}', log_filepath, file_handler)
time.sleep(0.1)
return log_filepath
return log_filepath
def insert_log(logger, log_message, log_filepath, file_handler):
log_filepath = check_log_size(log_filepath)
try:
logger.debug(log_message)
except PermissionError:
insert_log(logger, f'{log_message} {PermissionError}', log_filepath, file_handler)
time.sleep(0.1) # 延迟0.1秒
# 移除文件处理器
logger.removeHandler(file_handler)
# 初始化日志
# 在主程序中调用configure_logging函数,并传递file_handler给insert_log函数
log_filepath = create_new_log()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
file_handler = configure_logging()