拆分 douyin_logging (1412 → 5 个子模块 + 46 行 shim)
把 douyin/logging/douyin_logging.py 按职责拆成
douyin/logging/douyin_logging_pkg/ 子包:
- _common (21) 共享全局状态:_logging_configured / _logger_cache / _log_monitor
- handlers (206) 自定义 handler:RotatingDatedFileHandler / DatedFileHandler
- cleanup (282) 日志压缩与清理:compress_log_file / cleanup_old_logs / _load_*_policy
- monitor (337) 轮转监控:LogRotationMonitor / start/stop_log_monitor / get_log_stats
- config (652) 主配置入口:get_logger / configure_logging / log_function_call /
LogContext / get_caller_info / format_exception_info
原文件改为 46 行 re-export shim,15 个公共符号全部保留。
全局变量统一搬到 _common,子模块通过 ``from . import _common as _state``
访问 _state.X 形式(global 不能跨模块)。
子包名 douyin_logging_pkg 是为了避免与同目录下的 shim 文件
douyin_logging.py 冲突(同名包 vs 模块在 Python 中不能并存)。
回归:
- 6 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(含 unified_logger MDC 13 个用例)
- 旧 import 路径与新子包路径返回同一函数对象
- get_logger 缓存机制(第二次调用返回同一对象)正常工作
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
74209035f7
commit
9d1b0c1e36
7 files changed
+1597
-1409
No files matched your search
+43
-1409
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
"""douyin_logging_pkg - 日志系统子包。
|
||||
|
||||
原 douyin/logging/douyin_logging.py 拆成 5 个子模块:
|
||||
|
||||
- _common 共享全局状态:_logging_configured / _logger_cache / _log_monitor
|
||||
- handlers 自定义 handler:RotatingDatedFileHandler / DatedFileHandler
|
||||
- cleanup 压缩与清理:compress_log_file / cleanup_old_logs
|
||||
- monitor 监控线程:LogRotationMonitor / start_log_monitor / stop_log_monitor / get_log_stats
|
||||
- config 主配置入口:get_logger / configure_logging / log_function_call / LogContext
|
||||
|
||||
外部 import 路径不变:
|
||||
``from douyin.logging.douyin_logging import configure_logging`` 仍可用
|
||||
(原文件改成 re-export shim)。
|
||||
"""
|
||||
|
||||
from .handlers import (
|
||||
DatedFileHandler,
|
||||
RotatingDatedFileHandler,
|
||||
)
|
||||
from .cleanup import (
|
||||
_load_logging_cleanup_policy_from_config,
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
)
|
||||
from .monitor import (
|
||||
LogRotationMonitor,
|
||||
get_log_stats,
|
||||
start_log_monitor,
|
||||
stop_log_monitor,
|
||||
)
|
||||
from .config import (
|
||||
LogContext,
|
||||
configure_logging,
|
||||
format_exception_info,
|
||||
get_caller_info,
|
||||
get_logger,
|
||||
log_function_call,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"RotatingDatedFileHandler",
|
||||
"DatedFileHandler",
|
||||
"compress_log_file",
|
||||
"cleanup_old_logs",
|
||||
"_load_logging_cleanup_policy_from_config",
|
||||
"get_logger",
|
||||
"configure_logging",
|
||||
"log_function_call",
|
||||
"LogContext",
|
||||
"get_caller_info",
|
||||
"format_exception_info",
|
||||
"LogRotationMonitor",
|
||||
"start_log_monitor",
|
||||
"stop_log_monitor",
|
||||
"get_log_stats",
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""douyin_logging_pkg._common - 共享全局状态。
|
||||
|
||||
被 handlers / cleanup / config / monitor 子模块共用:
|
||||
- _logging_configured:configure_logging 是否已调用过
|
||||
- _logger_cache:get_logger 缓存
|
||||
- _log_monitor:LogRotationMonitor 实例(懒初始化)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Dict, Optional, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .monitor import LogRotationMonitor
|
||||
|
||||
# 全局日志配置
|
||||
_logging_configured = False
|
||||
_logger_cache: Dict[str, logging.Logger] = {}
|
||||
|
||||
# 日志监控器实例(懒启动 / 在 start_log_monitor 内创建)
|
||||
_log_monitor: "Optional[LogRotationMonitor]" = None
|
||||
@@ -0,0 +1,282 @@
|
||||
"""douyin_logging_pkg.cleanup - 日志压缩与清理策略。
|
||||
|
||||
- compress_log_file 压缩单个日志文件为 .gz
|
||||
- cleanup_old_logs 按大小 / 数量 / 天数三重清理
|
||||
- _load_logging_cleanup_policy_from_config 从 config.json 读取清理策略
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import gzip
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def compress_log_file(log_file: str) -> bool:
|
||||
"""压缩单个日志文件
|
||||
|
||||
参数:
|
||||
log_file: 日志文件路径
|
||||
|
||||
返回:
|
||||
是否压缩成功
|
||||
"""
|
||||
try:
|
||||
if not os.path.exists(log_file):
|
||||
return False
|
||||
|
||||
# 检查文件大小,只有较大文件才压缩
|
||||
file_size = os.path.getsize(log_file)
|
||||
if file_size < 1024 * 1024: # 小于1MB不压缩
|
||||
return False
|
||||
|
||||
compressed_file = log_file + ".gz"
|
||||
|
||||
# 如果压缩文件已存在,跳过
|
||||
if os.path.exists(compressed_file):
|
||||
return False
|
||||
|
||||
# 压缩文件
|
||||
with open(log_file, "rb") as f_in:
|
||||
with gzip.open(compressed_file, "wb", compresslevel=9) as f_out:
|
||||
shutil.copyfileobj(f_in, f_out)
|
||||
|
||||
# 验证压缩文件
|
||||
if os.path.exists(compressed_file):
|
||||
compressed_size = os.path.getsize(compressed_file)
|
||||
if compressed_size > 0:
|
||||
# 删除原文件
|
||||
os.remove(log_file)
|
||||
try:
|
||||
print(
|
||||
f"[日志压缩] 压缩完成: {os.path.basename(log_file)} "
|
||||
f"({file_size/1024:.1f}KB -> {compressed_size/1024:.1f}KB, "
|
||||
f"压缩率: {compressed_size/file_size*100:.1f}%)"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
return False
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志压缩] 压缩失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def cleanup_old_logs(
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
keep_days: int = 30,
|
||||
max_total_size_gb: float = 10.0, # 最大总大小(GB)
|
||||
compress_after_days: int = 7, # 几天后压缩
|
||||
compress: bool = True,
|
||||
) -> Dict[str, int]:
|
||||
"""智能清理旧日志文件:支持时间、大小、压缩三重策略
|
||||
|
||||
参数:
|
||||
logs_dir: 日志目录路径
|
||||
base_name: 日志文件基础名称(不含日期和扩展名),如 "unified"
|
||||
keep_days: 保留天数,默认30天
|
||||
max_total_size_gb: 最大总大小(GB),默认10GB
|
||||
compress_after_days: 几天后压缩,默认7天
|
||||
compress: 是否启用压缩,默认True
|
||||
|
||||
返回:
|
||||
清理统计信息
|
||||
"""
|
||||
stats = {
|
||||
"deleted": 0,
|
||||
"compressed": 0,
|
||||
"total_size_mb": 0.0,
|
||||
"freed_space_mb": 0.0,
|
||||
}
|
||||
|
||||
def _safe_get_mtime(path: str) -> float:
|
||||
try:
|
||||
return os.path.getmtime(path)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
def _safe_get_size(path: str) -> int:
|
||||
try:
|
||||
return os.path.getsize(path)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
try:
|
||||
if not os.path.exists(logs_dir):
|
||||
return stats
|
||||
|
||||
# 收集所有相关日志文件(包括压缩文件)
|
||||
patterns = [
|
||||
os.path.join(logs_dir, f"{base_name}_*.log"),
|
||||
os.path.join(logs_dir, f"{base_name}_*.log.gz"),
|
||||
]
|
||||
|
||||
all_files: list[str] = []
|
||||
for pattern in patterns:
|
||||
for p in glob.glob(pattern):
|
||||
# 并发轮转/删除时避免后续排序抛 FileNotFoundError
|
||||
if os.path.exists(p):
|
||||
all_files.append(p)
|
||||
|
||||
if not all_files:
|
||||
return stats
|
||||
|
||||
# 按修改时间排序(最新的在前)
|
||||
all_files.sort(key=_safe_get_mtime, reverse=True)
|
||||
|
||||
# 计算总大小
|
||||
total_size = sum(_safe_get_size(f) for f in all_files if os.path.exists(f))
|
||||
stats["total_size_mb"] = total_size / 1024 / 1024
|
||||
|
||||
# 如果总大小超过限制,先删除最旧的文件
|
||||
max_total_size_bytes = max_total_size_gb * 1024 * 1024 * 1024
|
||||
if total_size > max_total_size_bytes:
|
||||
# 按时间排序,删除最旧的
|
||||
sorted_files = sorted(
|
||||
[f for f in all_files if os.path.exists(f)],
|
||||
key=_safe_get_mtime,
|
||||
)
|
||||
|
||||
for log_file in sorted_files:
|
||||
if total_size <= max_total_size_bytes:
|
||||
break
|
||||
|
||||
try:
|
||||
file_size = _safe_get_size(log_file)
|
||||
os.remove(log_file)
|
||||
total_size -= file_size
|
||||
stats["deleted"] += 1
|
||||
stats["freed_space_mb"] += file_size / 1024 / 1024
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 删除文件失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 处理每个文件:压缩或删除
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
compress_date = datetime.now() - timedelta(days=compress_after_days)
|
||||
|
||||
for log_file in all_files:
|
||||
try:
|
||||
if not os.path.exists(log_file):
|
||||
continue
|
||||
|
||||
# 从文件名提取日期
|
||||
filename = os.path.basename(log_file)
|
||||
# 处理压缩文件扩展名
|
||||
if filename.endswith(".gz"):
|
||||
filename = filename[:-3]
|
||||
|
||||
# 提取日期部分
|
||||
date_part = filename.replace(f"{base_name}_", "").split(".")[0]
|
||||
|
||||
try:
|
||||
file_date = datetime.strptime(date_part, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# 如果超过保留天数,删除
|
||||
if file_date < cutoff_date:
|
||||
file_size = os.path.getsize(log_file)
|
||||
os.remove(log_file)
|
||||
stats["deleted"] += 1
|
||||
stats["freed_space_mb"] += file_size / 1024 / 1024
|
||||
|
||||
# 如果超过压缩天数且未压缩,压缩
|
||||
elif (
|
||||
compress
|
||||
and file_date < compress_date
|
||||
and not log_file.endswith(".gz")
|
||||
):
|
||||
if compress_log_file(log_file):
|
||||
stats["compressed"] += 1
|
||||
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 处理文件失败 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 输出统计信息
|
||||
if stats["deleted"] > 0 or stats["compressed"] > 0:
|
||||
try:
|
||||
print(
|
||||
f"[日志清理] 完成 - 删除:{stats['deleted']}, 压缩:{stats['compressed']}, "
|
||||
f"释放:{stats['freed_space_mb']:.1f}MB"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志清理] 清理过程出错: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
|
||||
|
||||
def _load_logging_cleanup_policy_from_config() -> tuple[int, float, int, bool]:
|
||||
"""从 config/config.json 读取日志清理策略。
|
||||
|
||||
返回:
|
||||
(keep_days, max_total_size_gb, compress_after_days, compress)
|
||||
|
||||
说明:
|
||||
- 只负责读取与容错;不做“阈值联动”的业务决策。
|
||||
- 读取失败时回退到模块默认值。
|
||||
"""
|
||||
keep_days = 30
|
||||
max_total_size_gb = 10.0
|
||||
compress_after_days = 7
|
||||
compress = True
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if not os.path.exists(config_path):
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
|
||||
log_cfg = cfg.get("logging", {})
|
||||
if isinstance(log_cfg, dict):
|
||||
keep_days = int(log_cfg.get("keep_days", keep_days))
|
||||
max_total_size_gb = float(
|
||||
log_cfg.get("max_total_size_gb", max_total_size_gb)
|
||||
)
|
||||
compress_after_days = int(
|
||||
log_cfg.get("compress_after_days", compress_after_days)
|
||||
)
|
||||
compress = bool(log_cfg.get("compress_logs", compress))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 基础兜底,避免异常配置导致“全部删光/不清理”
|
||||
if keep_days < 0:
|
||||
keep_days = 0
|
||||
if compress_after_days < 0:
|
||||
compress_after_days = 0
|
||||
if max_total_size_gb <= 0:
|
||||
# 若用户配置为 0/负数,视为禁用“按总量限制”,回退到默认
|
||||
max_total_size_gb = 10.0
|
||||
|
||||
return keep_days, max_total_size_gb, compress_after_days, compress
|
||||
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
"""douyin_logging_pkg.config - 日志配置与工具。
|
||||
|
||||
- get_logger 带缓存的 logger 获取
|
||||
- configure_logging 主配置入口(应用 handlers + cleanup + monitor)
|
||||
- log_function_call 性能装饰器:记录函数调用耗时与异常
|
||||
- LogContext 上下文管理器:记录代码块执行时间
|
||||
- get_caller_info 栈帧信息抓取
|
||||
- format_exception_info 异常堆栈格式化
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import _common as _state
|
||||
from .handlers import DatedFileHandler, RotatingDatedFileHandler
|
||||
from .cleanup import (
|
||||
_load_logging_cleanup_policy_from_config,
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
)
|
||||
from .monitor import start_log_monitor
|
||||
|
||||
|
||||
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取指定名称的 logger,如果未配置则自动配置"""
|
||||
if not _state._logging_configured:
|
||||
configure_logging()
|
||||
|
||||
# Ensure name is never None
|
||||
if name is None:
|
||||
# 自动获取调用者模块名
|
||||
frame = None
|
||||
try:
|
||||
frame = inspect.currentframe()
|
||||
if frame and frame.f_back:
|
||||
caller_frame = frame.f_back
|
||||
name = caller_frame.f_globals.get("__name__", "root")
|
||||
else:
|
||||
name = "root"
|
||||
except Exception:
|
||||
name = "root"
|
||||
finally:
|
||||
if frame is not None:
|
||||
try:
|
||||
del frame
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Final fallback to ensure name is a string
|
||||
logger_name: str = name if name is not None else "root"
|
||||
if logger_name not in _state._logger_cache:
|
||||
_state._logger_cache[logger_name] = logging.getLogger(logger_name)
|
||||
|
||||
return _state._logger_cache[logger_name]
|
||||
|
||||
|
||||
|
||||
|
||||
def configure_logging(
|
||||
log_level: Optional[str] = None,
|
||||
log_file: Optional[str] = None,
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB
|
||||
backup_count: int = 5, # 同一日期内保留的文件数
|
||||
enable_console: bool = True,
|
||||
enable_file: bool = True,
|
||||
keep_days: Optional[int] = None, # 保留日志天数
|
||||
use_dated_logs: Optional[bool] = None, # 是否使用按日期分割的日志
|
||||
compress_logs: Optional[bool] = None, # 是否压缩旧日志
|
||||
max_total_size_gb: float = 10.0, # 最大总日志大小(GB)
|
||||
compress_after_days: int = 7, # 几天后压缩
|
||||
enable_monitor: Optional[bool] = None, # 是否启用日志监控(仅启动阶段检查;运行时监控需显式开启)
|
||||
monitor_warning_mb: Optional[float] = None, # 监控警告大小(MB)
|
||||
monitor_critical_mb: Optional[float] = None, # 监控严重大小(MB)
|
||||
) -> None:
|
||||
"""配置日志系统
|
||||
|
||||
参数:
|
||||
log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL),默认从 config.json 读取
|
||||
log_file: 日志文件基础路径,默认使用 logs/unified.log(会被转换为 logs/unified)
|
||||
max_bytes: 单个日志文件最大大小(字节),超过后轮转,默认100MB
|
||||
backup_count: 保留的备份文件数量,默认10
|
||||
enable_console: 是否输出到控制台
|
||||
enable_file: 是否输出到文件
|
||||
keep_days: 保留日志的天数,超过此天数的日志将被自动删除,默认30天
|
||||
use_dated_logs: 是否使用按日期分割的日志,默认True
|
||||
compress_logs: 是否压缩旧日志,默认True
|
||||
max_total_size_gb: 最大总日志大小(GB),超过后删除最旧文件,默认10GB
|
||||
compress_after_days: 几天后压缩日志,默认7天
|
||||
enable_monitor: 是否启用日志监控(默认从 config.json 读取;仅影响启动阶段检查)
|
||||
monitor_warning_mb: 监控警告大小阈值(MB),默认500MB
|
||||
monitor_critical_mb: 监控严重大小阈值(MB),默认2000MB
|
||||
"""
|
||||
|
||||
# rotation 相关默认值(函数级),确保在所有分支可用,避免可能的未赋值使用
|
||||
rotation_enabled = False
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
|
||||
# 从 config.json 读取配置
|
||||
if (
|
||||
log_level is None
|
||||
or log_file is None
|
||||
or keep_days is None
|
||||
or use_dated_logs is None
|
||||
):
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
config_path = path_config.get_config_path()
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
if log_level is None:
|
||||
log_level = config.get("log_level", "INFO")
|
||||
if log_file is None:
|
||||
# 优先读取 log_unified_path,其次读取 logging.file_path
|
||||
log_file = config.get("log_unified_path") or config.get(
|
||||
"logging", {}
|
||||
).get("file_path", "logs/unified.log")
|
||||
log_config = config.get("logging", {})
|
||||
if keep_days is None:
|
||||
keep_days = log_config.get("keep_days", 30)
|
||||
if use_dated_logs is None:
|
||||
use_dated_logs = log_config.get("use_dated_logs", True)
|
||||
if compress_logs is None:
|
||||
compress_logs = log_config.get("compress_logs", True)
|
||||
if max_total_size_gb == 10.0: # 如果是默认值,从配置读取
|
||||
max_total_size_gb = log_config.get("max_total_size_gb", 10.0)
|
||||
if compress_after_days == 7: # 如果是默认值,从配置读取
|
||||
compress_after_days = log_config.get("compress_after_days", 7)
|
||||
|
||||
# 读取 monitor 配置
|
||||
if enable_monitor is None:
|
||||
enable_monitor = bool(log_config.get("enable_monitor", False))
|
||||
if monitor_warning_mb is None:
|
||||
try:
|
||||
monitor_warning_mb = float(log_config.get("monitor_warning_mb", 500.0))
|
||||
except Exception:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
try:
|
||||
monitor_critical_mb = float(log_config.get("monitor_critical_mb", 2000.0))
|
||||
except Exception:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# 读取 rotation 配置(优先级高于函数默认参数)
|
||||
rotation_cfg = (
|
||||
log_config.get("rotation", {})
|
||||
if isinstance(log_config, dict)
|
||||
else {}
|
||||
)
|
||||
rotation_enabled = rotation_cfg.get("enabled", True)
|
||||
if rotation_cfg:
|
||||
# 支持按大小与按时间的配置
|
||||
max_bytes = rotation_cfg.get("max_bytes", max_bytes)
|
||||
backup_count = rotation_cfg.get("backup_count", backup_count)
|
||||
rotation_when = rotation_cfg.get("when")
|
||||
rotation_interval = rotation_cfg.get("interval", 1)
|
||||
else:
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
except Exception:
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
if log_file is None:
|
||||
log_file = "logs/unified.log"
|
||||
if keep_days is None:
|
||||
keep_days = 30
|
||||
if use_dated_logs is None:
|
||||
use_dated_logs = True
|
||||
if compress_logs is None:
|
||||
compress_logs = True
|
||||
|
||||
if enable_monitor is None:
|
||||
enable_monitor = False
|
||||
if monitor_warning_mb is None:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# rotation 默认值(当读取 config 出错时)
|
||||
rotation_when = None
|
||||
rotation_interval = 1
|
||||
rotation_enabled = False
|
||||
|
||||
# 规范化 monitor 默认值
|
||||
if enable_monitor is None:
|
||||
enable_monitor = False
|
||||
if monitor_warning_mb is None:
|
||||
monitor_warning_mb = 500.0
|
||||
if monitor_critical_mb is None:
|
||||
monitor_critical_mb = 2000.0
|
||||
|
||||
# 规范化日志级别
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
|
||||
|
||||
# 配置根 logger
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(numeric_level)
|
||||
|
||||
# 清除已有的 handlers(避免重复配置)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
# 简化的日志格式:时间戳 - [级别] - [模块] - 消息
|
||||
# 去掉了冗余的线程名、函数名、行号、traceId等信息,使日志更简洁
|
||||
detailed_format = "%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s"
|
||||
simple_format = "%(asctime)s - [%(levelname)s] - %(message)s"
|
||||
|
||||
# 控制台输出
|
||||
if enable_console:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(numeric_level)
|
||||
console_formatter = logging.Formatter(
|
||||
simple_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
console_handler.setFormatter(console_formatter)
|
||||
|
||||
class ConsoleSuppressFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return not getattr(record, "suppress_console_output", False)
|
||||
|
||||
console_handler.addFilter(ConsoleSuppressFilter())
|
||||
root_logger.addHandler(console_handler)
|
||||
|
||||
# 文件输出(按日期分割或传统轮转)
|
||||
if enable_file:
|
||||
try:
|
||||
# 确保日志目录存在
|
||||
if log_file is None:
|
||||
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
|
||||
if log_file:
|
||||
base_filename = log_file.replace(".log", "")
|
||||
else:
|
||||
base_filename = "logs/unified"
|
||||
log_dir = os.path.dirname(base_filename)
|
||||
|
||||
# 确保目录存在
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 使用增强的轮转Handler
|
||||
# 支持每次运行生成独立文件(per_run):在 base_filename 后追加运行时间戳,并在 handler 中关闭日期轮转
|
||||
per_run = False
|
||||
try:
|
||||
per_run = (
|
||||
bool(log_config.get("per_run", True))
|
||||
if isinstance(log_config, dict)
|
||||
else True
|
||||
)
|
||||
except Exception:
|
||||
per_run = True
|
||||
|
||||
# base_filename_base: 不带运行时间戳/扩展名的基础名,用于清理和监控
|
||||
base_filename_base = base_filename
|
||||
if per_run:
|
||||
run_ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
base_filename = f"{base_filename_base}_{run_ts}"
|
||||
|
||||
file_handler = RotatingDatedFileHandler(
|
||||
base_filename,
|
||||
date_format="%Y-%m-%d",
|
||||
max_bytes=max_bytes,
|
||||
backup_count=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
mode="a",
|
||||
errors="replace",
|
||||
compress_old=compress_logs if compress_logs is not None else True,
|
||||
per_run=per_run,
|
||||
)
|
||||
|
||||
# 启动时检查总日志大小:若超过警告阈值则同步清理一次(仅在启动执行)
|
||||
if keep_days is not None:
|
||||
try:
|
||||
# 计算当前日志总大小(MB)
|
||||
pattern = os.path.join(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
f"{os.path.basename(base_filename_base)}_*.log*",
|
||||
)
|
||||
total_size = 0
|
||||
for p in glob.glob(pattern):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
total_size += os.path.getsize(p)
|
||||
except Exception:
|
||||
pass
|
||||
total_size_mb = total_size / 1024.0 / 1024.0
|
||||
except Exception:
|
||||
total_size_mb = 0.0
|
||||
|
||||
try:
|
||||
if total_size_mb >= float(monitor_warning_mb or 500.0):
|
||||
# 同步清理一次(仅在启动阶段)
|
||||
cleanup_old_logs(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
os.path.basename(base_filename_base),
|
||||
keep_days=keep_days,
|
||||
max_total_size_gb=max_total_size_gb,
|
||||
compress_after_days=compress_after_days,
|
||||
compress=(
|
||||
compress_logs if compress_logs is not None else True
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 注意:按用户反馈,默认不在运行过程中做日志目录体积检查。
|
||||
# 仅当显式开启运行时监控时才启动后台线程(避免主流程中途 I/O 干扰与刷屏)。
|
||||
runtime_monitor_enabled = False
|
||||
try:
|
||||
runtime_monitor_enabled = bool(
|
||||
(log_config.get("enable_runtime_monitor", False) if isinstance(log_config, dict) else False)
|
||||
)
|
||||
except Exception:
|
||||
runtime_monitor_enabled = False
|
||||
|
||||
# 环境变量可强制开启(便于临时诊断)
|
||||
if os.environ.get("ENABLE_RUNTIME_LOG_MONITOR") == "1":
|
||||
runtime_monitor_enabled = True
|
||||
|
||||
if runtime_monitor_enabled:
|
||||
try:
|
||||
monitor_check_interval = 300
|
||||
try:
|
||||
if isinstance(log_config, dict):
|
||||
monitor_check_interval = int(
|
||||
log_config.get("monitor_check_interval", 300)
|
||||
)
|
||||
except Exception:
|
||||
monitor_check_interval = 300
|
||||
|
||||
start_log_monitor(
|
||||
logs_dir=log_dir or path_config.get_logs_dir(),
|
||||
base_name=os.path.basename(base_filename_base),
|
||||
warning_size_mb=float(monitor_warning_mb),
|
||||
critical_size_mb=float(monitor_critical_mb),
|
||||
check_interval=monitor_check_interval,
|
||||
enable_runtime_cleanup=bool(
|
||||
(log_config.get("enable_runtime_cleanup", False) if isinstance(log_config, dict) else False)
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
print(f"[日志配置] 启动运行时监控器失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 使用传统的RotatingFileHandler
|
||||
if log_file is None:
|
||||
log_file = "logs/unified.log" # 默认值
|
||||
log_dir = os.path.dirname(log_file)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 如果配置了按时间轮转(when),使用 TimedRotatingFileHandler
|
||||
try:
|
||||
if rotation_enabled and rotation_when:
|
||||
file_handler = logging.handlers.TimedRotatingFileHandler(
|
||||
log_file,
|
||||
when=rotation_when,
|
||||
interval=rotation_interval,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
else:
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file, # type: ignore[arg-type]
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception:
|
||||
# 回退到大小轮转
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_file, # type: ignore[arg-type]
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
)
|
||||
|
||||
file_handler.setLevel(numeric_level)
|
||||
# 使用自定义Formatter以支持traceId
|
||||
try:
|
||||
from douyin.logging.unified_logger import UnifiedFormatter
|
||||
|
||||
file_formatter = UnifiedFormatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
except ImportError:
|
||||
# 如果unified_logger不可用,使用标准Formatter
|
||||
file_formatter = logging.Formatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
# 添加traceId占位符处理
|
||||
class TraceIdFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
if not hasattr(record, "traceId"):
|
||||
record.traceId = "N/A"
|
||||
return super().format(record)
|
||||
|
||||
file_formatter = TraceIdFormatter(
|
||||
detailed_format, datefmt="%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
file_formatter.default_msec_format = "%s.%03d" # 毫秒精度
|
||||
file_handler.setFormatter(file_formatter)
|
||||
|
||||
class FileSuppressFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return not getattr(record, "suppress_file_output", False)
|
||||
|
||||
file_handler.addFilter(FileSuppressFilter())
|
||||
root_logger.addHandler(file_handler)
|
||||
except Exception as e:
|
||||
# 文件 handler 创建失败,只输出到控制台
|
||||
try:
|
||||
print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_state._logging_configured = True
|
||||
|
||||
|
||||
|
||||
|
||||
def log_function_call(
|
||||
logger: Optional[logging.Logger] = None,
|
||||
log_args: bool = True,
|
||||
log_result: bool = False,
|
||||
log_time: bool = True,
|
||||
min_duration: float = 0.0, # 只记录超过此耗时的调用
|
||||
):
|
||||
"""装饰器:记录函数调用信息(参数、返回值、耗时)
|
||||
|
||||
参数:
|
||||
logger: 使用的 logger,默认自动获取
|
||||
log_args: 是否记录函数参数
|
||||
log_result: 是否记录返回值
|
||||
log_time: 是否记录执行时间
|
||||
min_duration: 最小耗时阈值(秒),低于此值不记录耗时
|
||||
"""
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if logger is None:
|
||||
_logger = get_logger()
|
||||
else:
|
||||
_logger = logger
|
||||
|
||||
func_name = func.__name__
|
||||
start_time = time.time()
|
||||
|
||||
# 记录函数调用
|
||||
if log_args:
|
||||
args_str = ", ".join(
|
||||
[str(arg)[:100] for arg in args[:3]]
|
||||
) # 只记录前3个参数,避免过长
|
||||
kwargs_str = ", ".join(
|
||||
[f"{k}={str(v)[:50]}" for k, v in list(kwargs.items())[:3]]
|
||||
)
|
||||
call_info = (
|
||||
f"{func_name}({args_str}{', ' + kwargs_str if kwargs_str else ''})"
|
||||
)
|
||||
if len(args) > 3 or len(kwargs) > 3:
|
||||
call_info += "..."
|
||||
_logger.debug(f"调用函数: {call_info}")
|
||||
|
||||
# 执行函数
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
# 记录执行结果
|
||||
if log_time and elapsed >= min_duration:
|
||||
_logger.debug(f"函数 {func_name} 执行完成,耗时: {elapsed:.3f}秒")
|
||||
|
||||
if log_result:
|
||||
result_str = str(result)[:200] # 限制长度
|
||||
_logger.debug(f"函数 {func_name} 返回值: {result_str}")
|
||||
|
||||
return result
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
_logger.exception(
|
||||
f"函数 {func_name} 执行异常,耗时: {elapsed:.3f}秒", exc_info=True
|
||||
)
|
||||
raise
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
|
||||
|
||||
class LogContext:
|
||||
"""上下文管理器:记录代码块执行时间"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
level: str = "DEBUG",
|
||||
log_on_exit: bool = True,
|
||||
):
|
||||
self.message = message
|
||||
self.logger = logger or get_logger()
|
||||
self.level = getattr(logging, level.upper(), logging.DEBUG)
|
||||
self.log_on_exit = log_on_exit
|
||||
self.start_time: Optional[float] = None
|
||||
|
||||
def __enter__(self):
|
||||
self.start_time = time.time()
|
||||
self.logger.log(self.level, f"{self.message} [开始]")
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if not self.log_on_exit:
|
||||
return False
|
||||
|
||||
if self.start_time is None:
|
||||
elapsed = 0.0
|
||||
else:
|
||||
elapsed = time.time() - self.start_time
|
||||
|
||||
if exc_type is None:
|
||||
self.logger.log(self.level, f"{self.message} [完成] 耗时: {elapsed:.3f}秒")
|
||||
else:
|
||||
self.logger.log(
|
||||
logging.ERROR,
|
||||
f"{self.message} [异常] 耗时: {elapsed:.3f}秒",
|
||||
exc_info=(exc_type, exc_val, exc_tb),
|
||||
)
|
||||
|
||||
return False # 不抑制异常
|
||||
|
||||
|
||||
|
||||
|
||||
def get_caller_info(skip_frames: int = 0) -> Dict[str, Any]:
|
||||
"""获取调用者信息(模块名、函数名、行号)
|
||||
|
||||
参数:
|
||||
skip_frames: 跳过的栈帧数(用于在装饰器中获取真正的调用者)
|
||||
|
||||
返回:
|
||||
包含 module, function, line, file 的字典
|
||||
"""
|
||||
frame = None
|
||||
try:
|
||||
frame = inspect.currentframe()
|
||||
if frame:
|
||||
# 跳过当前函数和装饰器
|
||||
for _ in range(skip_frames + 2):
|
||||
if frame.f_back:
|
||||
frame = frame.f_back
|
||||
else:
|
||||
break
|
||||
|
||||
if frame:
|
||||
return {
|
||||
"module": os.path.basename(frame.f_code.co_filename),
|
||||
"function": frame.f_code.co_name,
|
||||
"line": frame.f_lineno,
|
||||
"file": frame.f_code.co_filename,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if frame is not None:
|
||||
try:
|
||||
del frame
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"module": "unknown",
|
||||
"function": "unknown",
|
||||
"line": 0,
|
||||
"file": "unknown",
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
def format_exception_info(exc_info=None) -> str:
|
||||
"""格式化异常信息为字符串
|
||||
|
||||
参数:
|
||||
exc_info: 异常信息元组 (type, value, traceback),默认使用 sys.exc_info()
|
||||
|
||||
返回:
|
||||
格式化的异常堆栈字符串
|
||||
"""
|
||||
if exc_info is None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
if exc_info[0] is None:
|
||||
return ""
|
||||
|
||||
try:
|
||||
# exc_info 应该是 (type, value, traceback) 元组
|
||||
if isinstance(exc_info, tuple) and len(exc_info) >= 3:
|
||||
exc_type, exc_value, exc_tb = exc_info[0], exc_info[1], exc_info[2]
|
||||
# 确保类型正确
|
||||
if isinstance(exc_value, BaseException):
|
||||
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,
|
||||
)
|
||||
)
|
||||
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'}"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""douyin_logging_pkg.handlers - 自定义日志 handler。
|
||||
|
||||
- RotatingDatedFileHandler 按日期 + 大小双轮转、自动压缩
|
||||
- DatedFileHandler 按日期分割(兼容包装)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class RotatingDatedFileHandler(logging.FileHandler):
|
||||
"""增强的日志处理器:支持日期+大小轮转和压缩
|
||||
|
||||
特性:
|
||||
1. 按日期分割日志文件(每天一个新文件)
|
||||
2. 当文件超过大小限制时,在日期内创建序号文件(如 unified_2024-01-15.1.log)
|
||||
3. 自动压缩超过保留天数的旧日志文件
|
||||
4. 智能清理策略:按时间、大小、数量三重限制
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_filename: str,
|
||||
date_format: str = "%Y-%m-%d",
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB
|
||||
backup_count: int = 5, # 同一日期内最多保留的文件数
|
||||
per_run: bool = False, # 是否为每次运行生成独立文件(包含运行时间戳)
|
||||
encoding: str = "utf-8-sig",
|
||||
mode: str = "a",
|
||||
errors: str = "replace",
|
||||
compress_old: bool = True, # 是否压缩旧日志
|
||||
):
|
||||
"""
|
||||
参数:
|
||||
base_filename: 基础文件名(不含日期和扩展名),如 "logs/unified"
|
||||
date_format: 日期格式,默认 "%Y-%m-%d"
|
||||
max_bytes: 单个日志文件最大大小(字节),默认100MB
|
||||
backup_count: 同一日期内保留的备份文件数量,默认10
|
||||
encoding: 文件编码,默认 "utf-8-sig"
|
||||
mode: 打开模式,默认 "a"
|
||||
errors: 错误处理,默认 "replace"
|
||||
compress_old: 是否压缩旧日志,默认True
|
||||
"""
|
||||
self.base_filename = base_filename
|
||||
self.date_format = date_format
|
||||
self.max_bytes = max_bytes
|
||||
self.backup_count = backup_count
|
||||
self.compress_old = compress_old
|
||||
self.per_run = per_run
|
||||
|
||||
self.current_date = datetime.now().strftime(date_format)
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
self.current_sequence = 0 # 当前文件序号
|
||||
self.per_run = per_run
|
||||
|
||||
# 确保目录存在
|
||||
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,
|
||||
)
|
||||
|
||||
# 优化:缓存日期检查
|
||||
self._date_check_counter = 0
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
def _get_filename_for_date(self, date_str: str, sequence: int = 0) -> str:
|
||||
"""根据日期和序号生成文件名"""
|
||||
if self.per_run:
|
||||
# 每次运行的文件名不再包含额外的日期字段(base_filename 已带运行时间戳)
|
||||
if sequence == 0:
|
||||
return f"{self.base_filename}.log"
|
||||
else:
|
||||
return f"{self.base_filename}.{sequence}.log"
|
||||
else:
|
||||
if sequence == 0:
|
||||
return f"{self.base_filename}_{date_str}.log"
|
||||
else:
|
||||
return f"{self.base_filename}_{date_str}.{sequence}.log"
|
||||
|
||||
def _get_next_filename(self, date_str: str) -> str:
|
||||
"""获取下一个可用的文件名"""
|
||||
# 首先检查序号0的文件
|
||||
filename = self._get_filename_for_date(date_str, 0)
|
||||
if not os.path.exists(filename) or os.path.getsize(filename) < self.max_bytes:
|
||||
return filename
|
||||
|
||||
# 如果序号0的文件已满,查找可用的序号
|
||||
for sequence in range(1, self.backup_count + 1):
|
||||
filename = self._get_filename_for_date(date_str, sequence)
|
||||
if (
|
||||
not os.path.exists(filename)
|
||||
or os.path.getsize(filename) < self.max_bytes
|
||||
):
|
||||
return filename
|
||||
|
||||
# 如果所有序号都满了,返回最后一个(会触发覆盖最旧的)
|
||||
return self._get_filename_for_date(date_str, self.backup_count)
|
||||
|
||||
def _rotate_file(self, date_str: str) -> None:
|
||||
"""轮转到新文件"""
|
||||
self.close()
|
||||
|
||||
# 获取新的文件名
|
||||
new_filename = self._get_next_filename(date_str)
|
||||
|
||||
# 如果文件已存在且已满,删除最旧的文件
|
||||
if (
|
||||
os.path.exists(new_filename)
|
||||
and os.path.getsize(new_filename) >= self.max_bytes
|
||||
):
|
||||
try:
|
||||
os.remove(new_filename)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.current_filename = new_filename
|
||||
|
||||
# 重新初始化文件流
|
||||
self.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
"""发送日志记录,支持日期和大小轮转"""
|
||||
# 检查是否需要日期轮转
|
||||
self._check_date_rotation()
|
||||
|
||||
# 检查是否需要大小轮转
|
||||
if self.stream and hasattr(self.stream, "tell"):
|
||||
try:
|
||||
current_size = self.stream.tell()
|
||||
if current_size >= self.max_bytes:
|
||||
self._rotate_file(self.current_date)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
super().emit(record)
|
||||
|
||||
def _check_date_rotation(self) -> None:
|
||||
"""检查日期轮转(优化版本)"""
|
||||
# 每100条记录或每1秒检查一次日期
|
||||
self._date_check_counter += 1
|
||||
should_check_date = (
|
||||
self._date_check_counter >= 100
|
||||
or (datetime.now() - self._last_date_check_time).total_seconds() >= 1.0
|
||||
)
|
||||
|
||||
if should_check_date:
|
||||
today = datetime.now().strftime(self.date_format)
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
if not self.per_run and today != self.current_date:
|
||||
# 日期变化,轮转到新日期(per_run 模式下不按日期轮转)
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
|
||||
# 确保目录存在
|
||||
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()
|
||||
|
||||
# 重置计数器
|
||||
self._date_check_counter = 0
|
||||
|
||||
|
||||
|
||||
|
||||
class DatedFileHandler(RotatingDatedFileHandler):
|
||||
"""兼容性类:保留原DatedFileHandler接口"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_filename: str,
|
||||
date_format: str = "%Y-%m-%d",
|
||||
encoding: str = "utf-8-sig",
|
||||
mode: str = "a",
|
||||
errors: str = "replace",
|
||||
):
|
||||
# 为了兼容,设置较大的max_bytes(1GB)以基本只按日期分割
|
||||
super().__init__(
|
||||
base_filename=base_filename,
|
||||
date_format=date_format,
|
||||
max_bytes=1024 * 1024 * 1024, # 1GB
|
||||
backup_count=1,
|
||||
encoding=encoding,
|
||||
mode=mode,
|
||||
errors=errors,
|
||||
compress_old=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""douyin_logging_pkg.monitor - 日志轮转 / 大小监控。
|
||||
|
||||
- LogRotationMonitor 轮转监控线程(按间隔检查日志大小并触发清理)
|
||||
- start_log_monitor 启动监控(懒创建实例)
|
||||
- stop_log_monitor 停止监控
|
||||
- get_log_stats 汇总日志统计信息
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import _common as _state
|
||||
|
||||
|
||||
class LogRotationMonitor:
|
||||
"""日志轮转监控器:监控日志大小、轮转频率并发出告警"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
warning_size_mb: float = 500.0, # 警告大小(MB)
|
||||
critical_size_mb: float = 2000.0, # 严重大小(MB)
|
||||
check_interval: int = 300, # 检查间隔(秒)
|
||||
rotation_threshold: int = 10, # 轮转频率阈值(每天)
|
||||
alert_callback: Optional[Callable[[str, str], None]] = None,
|
||||
enable_runtime_cleanup: bool = False,
|
||||
):
|
||||
"""
|
||||
参数:
|
||||
logs_dir: 日志目录
|
||||
base_name: 日志文件基础名称
|
||||
warning_size_mb: 警告大小阈值(MB)
|
||||
critical_size_mb: 严重大小阈值(MB)
|
||||
check_interval: 检查间隔(秒)
|
||||
rotation_threshold: 轮转频率阈值(每天)
|
||||
alert_callback: 告警回调函数,参数:(level, message)
|
||||
"""
|
||||
self.logs_dir = logs_dir
|
||||
self.base_name = base_name
|
||||
self.warning_size_mb = warning_size_mb
|
||||
self.critical_size_mb = critical_size_mb
|
||||
self.check_interval = check_interval
|
||||
self.rotation_threshold = rotation_threshold
|
||||
self.alert_callback = alert_callback
|
||||
|
||||
self._running = False
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._last_rotation_count = 0
|
||||
self._last_check_time = datetime.now()
|
||||
# 清理状态,避免并发触发大量清理操作
|
||||
self._cleanup_lock = threading.Lock()
|
||||
self._cleanup_running = False
|
||||
# 是否允许在运行过程中触发自动清理(默认不允许)
|
||||
self.enable_runtime_cleanup = bool(enable_runtime_cleanup)
|
||||
|
||||
# 告警输出限流:避免在运行时开启监控时刷屏
|
||||
self._last_warning_print_ts = 0.0
|
||||
self._last_critical_print_ts = 0.0
|
||||
self._min_alert_print_interval_sec = 3600.0
|
||||
|
||||
def start(self) -> None:
|
||||
"""启动监控器"""
|
||||
if self._running:
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._monitor_loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止监控器"""
|
||||
self._running = False
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=5)
|
||||
|
||||
def _monitor_loop(self) -> None:
|
||||
"""监控循环"""
|
||||
while self._running:
|
||||
try:
|
||||
self._check_logs()
|
||||
time.sleep(self.check_interval)
|
||||
except Exception as e:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志监控器异常: {e}")
|
||||
|
||||
def _check_logs(self) -> None:
|
||||
"""检查日志状态"""
|
||||
try:
|
||||
# 收集所有日志文件
|
||||
pattern = os.path.join(self.logs_dir, f"{self.base_name}_*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
if not log_files:
|
||||
return
|
||||
|
||||
# 计算总大小
|
||||
total_size = sum(os.path.getsize(f) for f in log_files if os.path.exists(f))
|
||||
total_size_mb = total_size / 1024 / 1024
|
||||
|
||||
# 检查大小告警
|
||||
if total_size_mb >= self.critical_size_mb:
|
||||
message = f"日志总大小严重超限: {total_size_mb:.1f}MB >= {self.critical_size_mb}MB"
|
||||
if self.alert_callback:
|
||||
self.alert_callback("CRITICAL", message)
|
||||
else:
|
||||
now_ts = time.time()
|
||||
if (
|
||||
now_ts - self._last_critical_print_ts
|
||||
>= self._min_alert_print_interval_sec
|
||||
):
|
||||
print(f"[日志监控] CRITICAL: {message}")
|
||||
self._last_critical_print_ts = now_ts
|
||||
|
||||
elif total_size_mb >= self.warning_size_mb:
|
||||
message = (
|
||||
f"日志总大小警告: {total_size_mb:.1f}MB >= {self.warning_size_mb}MB"
|
||||
)
|
||||
if self.alert_callback:
|
||||
self.alert_callback("WARNING", message)
|
||||
else:
|
||||
now_ts = time.time()
|
||||
if (
|
||||
now_ts - self._last_warning_print_ts
|
||||
>= self._min_alert_print_interval_sec
|
||||
):
|
||||
print(f"[日志监控] WARNING: {message}")
|
||||
self._last_warning_print_ts = now_ts
|
||||
# 运行时不再自动触发清理,清理仅在启动阶段执行以避免中途 I/O 干扰
|
||||
# 检查轮转频率
|
||||
current_time = datetime.now()
|
||||
if (
|
||||
current_time - self._last_check_time
|
||||
).total_seconds() >= 86400: # 24小时
|
||||
# 计算今天的文件数量
|
||||
today_str = current_time.strftime("%Y-%m-%d")
|
||||
today_files = [f for f in log_files if today_str in f]
|
||||
|
||||
if len(today_files) >= self.rotation_threshold:
|
||||
message = f"日志轮转频率过高: 今天已轮转 {len(today_files)} 次 (>= {self.rotation_threshold})"
|
||||
if self.alert_callback:
|
||||
self.alert_callback("WARNING", message)
|
||||
else:
|
||||
print(f"[日志监控] WARNING: {message}")
|
||||
|
||||
self._last_check_time = current_time
|
||||
|
||||
except Exception as e:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志检查失败: {e}")
|
||||
|
||||
def _schedule_cleanup_async(self) -> None:
|
||||
"""如果没有正在运行的清理任务,则在后台线程中启动一次清理。"""
|
||||
# 如果未开启运行时清理功能,直接返回(清理仅限启动阶段)
|
||||
if not getattr(self, "enable_runtime_cleanup", False):
|
||||
return
|
||||
|
||||
# 用锁做“唯一运行”判定,避免竞态导致并发启动多个清理线程
|
||||
with self._cleanup_lock:
|
||||
if self._cleanup_running:
|
||||
return
|
||||
self._cleanup_running = True
|
||||
|
||||
keep_days, cfg_max_total_size_gb, compress_after_days, compress = (
|
||||
_load_logging_cleanup_policy_from_config()
|
||||
)
|
||||
|
||||
# 监控告警阈值与清理联动:当触发 WARNING 时,把总量上限压到 warning 阈值附近
|
||||
# 这样“>=500MB 报警”能实际驱动清理生效(而不是仍按 10GB 上限导致无动作)。
|
||||
try:
|
||||
warning_target_gb = max(0.05, float(self.warning_size_mb) / 1024.0)
|
||||
except Exception:
|
||||
warning_target_gb = 0.5
|
||||
|
||||
effective_max_total_size_gb = min(cfg_max_total_size_gb, warning_target_gb)
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
# 使用模块内的 cleanup_old_logs 执行清理,采用默认策略(保留30天、10GB上限)
|
||||
try:
|
||||
cleanup_old_logs(
|
||||
logs_dir=self.logs_dir,
|
||||
base_name=self.base_name,
|
||||
keep_days=keep_days,
|
||||
max_total_size_gb=effective_max_total_size_gb,
|
||||
compress_after_days=compress_after_days,
|
||||
compress=compress,
|
||||
)
|
||||
except Exception as e:
|
||||
try:
|
||||
if self.alert_callback:
|
||||
self.alert_callback("ERROR", f"日志自动清理失败: {e}")
|
||||
else:
|
||||
print(f"[日志监控] 日志自动清理失败: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
with self._cleanup_lock:
|
||||
self._cleanup_running = False
|
||||
except Exception:
|
||||
self._cleanup_running = False
|
||||
|
||||
t = threading.Thread(target=_worker, daemon=True)
|
||||
t.start()
|
||||
|
||||
|
||||
|
||||
|
||||
def start_log_monitor(
|
||||
logs_dir: str,
|
||||
base_name: str,
|
||||
warning_size_mb: float = 500.0,
|
||||
critical_size_mb: float = 2000.0,
|
||||
check_interval: int = 300,
|
||||
alert_callback: Optional[Callable[[str, str], None]] = None,
|
||||
enable_runtime_cleanup: bool = False,
|
||||
) -> None:
|
||||
"""启动日志轮转监控器
|
||||
|
||||
参数:
|
||||
logs_dir: 日志目录
|
||||
base_name: 日志文件基础名称
|
||||
warning_size_mb: 警告大小阈值(MB)
|
||||
critical_size_mb: 严重大小阈值(MB)
|
||||
check_interval: 检查间隔(秒)
|
||||
alert_callback: 告警回调函数
|
||||
"""
|
||||
|
||||
if _state._log_monitor:
|
||||
_state._log_monitor.stop()
|
||||
|
||||
_state._log_monitor = LogRotationMonitor(
|
||||
logs_dir=logs_dir,
|
||||
base_name=base_name,
|
||||
warning_size_mb=warning_size_mb,
|
||||
critical_size_mb=critical_size_mb,
|
||||
check_interval=check_interval,
|
||||
alert_callback=alert_callback,
|
||||
enable_runtime_cleanup=enable_runtime_cleanup,
|
||||
)
|
||||
_state._log_monitor.start()
|
||||
|
||||
|
||||
|
||||
|
||||
def stop_log_monitor() -> None:
|
||||
"""停止日志轮转监控器"""
|
||||
|
||||
if _state._log_monitor:
|
||||
_state._log_monitor.stop()
|
||||
_log_monitor = None
|
||||
|
||||
|
||||
|
||||
|
||||
def get_log_stats(logs_dir: str, base_name: str) -> Dict[str, Any]:
|
||||
"""获取日志统计信息
|
||||
|
||||
返回:
|
||||
包含文件数量、总大小、压缩率等信息的字典
|
||||
"""
|
||||
stats = {
|
||||
"total_files": 0,
|
||||
"total_size_mb": 0.0,
|
||||
"compressed_files": 0,
|
||||
"compressed_size_mb": 0.0,
|
||||
"compression_ratio": 0.0,
|
||||
"oldest_file": None,
|
||||
"newest_file": None,
|
||||
}
|
||||
|
||||
try:
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log*")
|
||||
log_files = glob.glob(pattern)
|
||||
|
||||
if not log_files:
|
||||
return stats
|
||||
|
||||
stats["total_files"] = len(log_files)
|
||||
|
||||
# 计算大小统计
|
||||
uncompressed_size = 0
|
||||
compressed_size = 0
|
||||
|
||||
file_times = []
|
||||
for log_file in log_files:
|
||||
if os.path.exists(log_file):
|
||||
size = os.path.getsize(log_file)
|
||||
stats["total_size_mb"] += size / 1024 / 1024
|
||||
|
||||
if log_file.endswith(".gz"):
|
||||
stats["compressed_files"] += 1
|
||||
compressed_size += size
|
||||
else:
|
||||
uncompressed_size += size
|
||||
|
||||
# 记录文件时间
|
||||
try:
|
||||
mtime = os.path.getmtime(log_file)
|
||||
file_times.append((mtime, log_file))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 计算压缩率
|
||||
if uncompressed_size > 0 and compressed_size > 0:
|
||||
# 压缩率 = 压缩后大小 / 原始大小
|
||||
stats["compression_ratio"] = compressed_size / (
|
||||
uncompressed_size + compressed_size
|
||||
)
|
||||
|
||||
# 找出最老和最新的文件
|
||||
if file_times:
|
||||
file_times.sort()
|
||||
stats["oldest_file"] = os.path.basename(file_times[0][1])
|
||||
stats["newest_file"] = os.path.basename(file_times[-1][1])
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# 自动配置日志(在模块导入时)
|
||||
if not _state._logging_configured:
|
||||
# 延迟配置,避免在导入时读取 config.json 失败
|
||||
try:
|
||||
configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
Reference in new issue
Block a user