Auto commit: 2025-12-21 22:45:00 - Hourly auto save
This commit is contained in:
1 parent
1a63852bde
commit
5b8dd6e5d4
17 files changed
+1921
-88
No files matched your search
+49
-32
@@ -34,7 +34,7 @@ _logger_cache: Dict[str, logging.Logger] = {}
|
||||
|
||||
class DatedFileHandler(logging.FileHandler):
|
||||
"""按日期创建日志文件的Handler,每天创建一个新文件"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_filename: str,
|
||||
@@ -55,19 +55,19 @@ class DatedFileHandler(logging.FileHandler):
|
||||
self.date_format = date_format
|
||||
self.current_date = datetime.now().strftime(date_format)
|
||||
self.current_filename = f"{base_filename}_{self.current_date}.log"
|
||||
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
super().__init__(
|
||||
self.current_filename,
|
||||
mode=mode,
|
||||
encoding=encoding,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
"""发送日志记录,如果日期变化则切换到新文件"""
|
||||
today = datetime.now().strftime(self.date_format)
|
||||
@@ -76,22 +76,22 @@ class DatedFileHandler(logging.FileHandler):
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = f"{self.base_filename}_{self.current_date}.log"
|
||||
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
# 重新初始化文件流
|
||||
self.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
|
||||
super().emit(record)
|
||||
|
||||
|
||||
def cleanup_old_logs(logs_dir: str, base_name: str, keep_days: int = 30) -> None:
|
||||
"""删除过旧的日志文件
|
||||
|
||||
|
||||
参数:
|
||||
logs_dir: 日志目录路径
|
||||
base_name: 日志文件基础名称(不含日期和扩展名),如 "unified"
|
||||
@@ -100,31 +100,31 @@ def cleanup_old_logs(logs_dir: str, base_name: str, keep_days: int = 30) -> None
|
||||
try:
|
||||
if not os.path.exists(logs_dir):
|
||||
return
|
||||
|
||||
|
||||
# 构建匹配模式,例如: logs/unified_*.log
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
|
||||
if not log_files:
|
||||
return
|
||||
|
||||
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
deleted_count = 0
|
||||
|
||||
|
||||
for log_file in log_files:
|
||||
try:
|
||||
# 从文件名提取日期(例如: unified_2024-01-15.log -> 2024-01-15)
|
||||
filename = os.path.basename(log_file)
|
||||
# 移除基础名称和下划线,移除.log扩展名
|
||||
date_str = filename.replace(f"{base_name}_", "").replace(".log", "")
|
||||
|
||||
|
||||
# 尝试解析日期
|
||||
try:
|
||||
file_date = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
# 如果日期格式不匹配,尝试其他格式或跳过
|
||||
continue
|
||||
|
||||
|
||||
# 如果文件日期早于截止日期,删除文件
|
||||
if file_date < cutoff_date:
|
||||
os.remove(log_file)
|
||||
@@ -135,10 +135,12 @@ def cleanup_old_logs(logs_dir: str, base_name: str, keep_days: int = 30) -> None
|
||||
print(f"[日志清理] 删除日志文件失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if deleted_count > 0:
|
||||
try:
|
||||
print(f"[日志清理] 已删除 {deleted_count} 个超过 {keep_days} 天的旧日志文件")
|
||||
print(
|
||||
f"[日志清理] 已删除 {deleted_count} 个超过 {keep_days} 天的旧日志文件"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
@@ -207,7 +209,12 @@ def configure_logging(
|
||||
global _logging_configured
|
||||
|
||||
# 从 config.json 读取配置
|
||||
if log_level is None or log_file is None or keep_days is None or use_dated_logs is None:
|
||||
if (
|
||||
log_level is None
|
||||
or log_file is None
|
||||
or keep_days is None
|
||||
or use_dated_logs is None
|
||||
):
|
||||
try:
|
||||
import json
|
||||
|
||||
@@ -270,7 +277,7 @@ def configure_logging(
|
||||
log_file = "logs/unified.log" # 默认值
|
||||
if not os.path.isabs(log_file):
|
||||
log_file = os.path.join(path_config.PROJECT_ROOT, log_file)
|
||||
|
||||
|
||||
# 如果是使用日期日志,提取基础文件名(移除扩展名)
|
||||
if use_dated_logs:
|
||||
# 从完整路径提取基础名称,例如: logs/unified.log -> logs/unified
|
||||
@@ -279,11 +286,11 @@ def configure_logging(
|
||||
else:
|
||||
base_filename = "logs/unified"
|
||||
log_dir = os.path.dirname(base_filename)
|
||||
|
||||
|
||||
# 确保目录存在
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
# 使用按日期分割的Handler
|
||||
file_handler = DatedFileHandler(
|
||||
base_filename,
|
||||
@@ -292,12 +299,14 @@ def configure_logging(
|
||||
mode="a",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
|
||||
# 启动时清理旧日志
|
||||
if keep_days is not None:
|
||||
cleanup_old_logs(log_dir or path_config.get_logs_dir(),
|
||||
os.path.basename(base_filename),
|
||||
keep_days)
|
||||
cleanup_old_logs(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
os.path.basename(base_filename),
|
||||
keep_days,
|
||||
)
|
||||
else:
|
||||
# 使用传统的RotatingFileHandler
|
||||
if log_file is None:
|
||||
@@ -305,7 +314,7 @@ def configure_logging(
|
||||
log_dir = os.path.dirname(log_file)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file, # type: ignore[arg-type]
|
||||
maxBytes=max_bytes,
|
||||
@@ -313,7 +322,7 @@ def configure_logging(
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
|
||||
file_handler.setLevel(numeric_level)
|
||||
file_formatter = logging.Formatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S.%f"
|
||||
@@ -510,15 +519,23 @@ def format_exception_info(exc_info=None) -> str:
|
||||
return "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
|
||||
else:
|
||||
# 如果不是异常实例,创建一个包装
|
||||
return "".join(traceback.format_exception(
|
||||
exc_type,
|
||||
BaseException(str(exc_value)) if exc_value else BaseException("Unknown error"),
|
||||
exc_tb
|
||||
))
|
||||
return "".join(
|
||||
traceback.format_exception(
|
||||
exc_type,
|
||||
(
|
||||
BaseException(str(exc_value))
|
||||
if exc_value
|
||||
else BaseException("Unknown error")
|
||||
),
|
||||
exc_tb,
|
||||
)
|
||||
)
|
||||
else:
|
||||
return "".join(traceback.format_exception(*exc_info))
|
||||
except Exception:
|
||||
return f"异常: {exc_info[1] if len(exc_info) > 1 and exc_info[1] else 'Unknown'}"
|
||||
return (
|
||||
f"异常: {exc_info[1] if len(exc_info) > 1 and exc_info[1] else 'Unknown'}"
|
||||
)
|
||||
|
||||
|
||||
# 自动配置日志(在模块导入时)
|
||||
|
||||
Reference in new issue
Block a user