import logging import sys from datetime import datetime, timedelta import os LOG_DIR = "./logs" # 日志文件目录 LOG_RETENTION_DAYS = 7 # 日志保留天数 def _remove_old_logs(log_dir, retention_days): """删除超过保留天数的日志文件""" if not os.path.exists(log_dir): os.makedirs(log_dir) now = datetime.now() for filename in os.listdir(log_dir): file_path = os.path.join(log_dir, filename) if os.path.isfile(file_path) and filename.startswith("run_") and filename.endswith(".log"): # 提取文件日期 try: log_date_str = filename[4:14] log_date = datetime.strptime(log_date_str, "%Y-%m-%d") if now - log_date > timedelta(days=retention_days): os.remove(file_path) print(f"删除旧日志: {filename}") except ValueError: continue def _reset_logger(log): for handler in log.handlers: handler.close() log.removeHandler(handler) del handler log.handlers.clear() log.propagate = False console_handle = logging.StreamHandler(sys.stdout) console_handle.setFormatter( logging.Formatter( "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) ) # 获取当前日期并将其加入日志文件名 date_str = datetime.now().strftime("%Y-%m-%d") log_file_path = os.path.join(LOG_DIR, f"run_{date_str}.log") # 日志文件句柄 file_handle = logging.FileHandler(log_file_path, encoding="utf-8") file_handle.setFormatter( logging.Formatter( "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) ) log.addHandler(file_handle) log.addHandler(console_handle) # 清理旧日志 _remove_old_logs(LOG_DIR, LOG_RETENTION_DAYS) def _get_logger(): log = logging.getLogger("log") _reset_logger(log) log.setLevel(logging.INFO) return log # 日志句柄 logger = _get_logger()