Files
douyin_guaji-main/douyin/logging/douyin_logging.py
T

1178 lines
41 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
日志系统配置与工具模块
====================
功能:
1. 标准 logging 配置(支持日志轮转、级别管理)
2. 按日期分割日志(每天一个新日志文件)
3. 大小限制轮转(防止单个文件过大)
4. 自动压缩旧日志文件
5. 智能清理策略(大小、数量、时间三重限制)
6. 轮转监控和告警
7. 增强的日志记录工具(自动记录调用者信息、异常堆栈等)
8. 性能监控装饰器(记录函数调用耗时)
9. 上下文管理器(记录代码块执行时间)
"""
from __future__ import annotations
import os
import sys
import time
import logging
import logging.handlers
import traceback
import inspect
import glob
import gzip
import shutil
import threading
from datetime import datetime, timedelta
from typing import Optional, Callable, Any, Dict
from functools import wraps
import path_config
# 全局日志配置
_logging_configured = False
_logger_cache: Dict[str, logging.Logger] = {}
# 日志监控器实例
_log_monitor: Optional["LogRotationMonitor"] = None
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,
)
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,
}
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 = []
for pattern in patterns:
all_files.extend(glob.glob(pattern))
if not all_files:
return stats
# 按修改时间排序(最新的在前)
all_files.sort(key=os.path.getmtime, reverse=True)
# 计算总大小
total_size = sum(os.path.getsize(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(all_files, key=os.path.getmtime)
for log_file in sorted_files:
if total_size <= max_total_size_bytes:
break
try:
file_size = os.path.getsize(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 get_logger(name: Optional[str] = None) -> logging.Logger:
"""获取指定名称的 logger,如果未配置则自动配置"""
if not _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 _logger_cache:
_logger_cache[logger_name] = logging.getLogger(logger_name)
return _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: bool = True, # 是否启用日志监控
monitor_warning_mb: float = 500.0, # 监控警告大小(MB)
monitor_critical_mb: float = 2000.0, # 监控严重大小(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: 是否启用日志轮转监控,默认True
monitor_warning_mb: 监控警告大小阈值(MB),默认500MB
monitor_critical_mb: 监控严重大小阈值(MB),默认2000MB
"""
global _logging_configured
# 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)
# 读取 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
# rotation 默认值(当读取 config 出错时)
rotation_when = None
rotation_interval = 1
rotation_enabled = False
# 规范化日志级别
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.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - "
"[%(name)s:%(funcName)s:%(lineno)d] - [traceId:%(traceId)s] - %(message)s"
)
simple_format = (
"%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)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)
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,
)
# 启动时清理旧日志:始终以基础 base 名(不含运行时间戳)作为匹配前缀
if keep_days is not None:
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,
)
# 启动日志监控器
if enable_monitor:
try:
start_log_monitor(
logs_dir=log_dir or path_config.get_logs_dir(),
base_name=os.path.basename(base_filename_base),
warning_size_mb=monitor_warning_mb,
critical_size_mb=monitor_critical_mb,
)
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 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)
root_logger.addHandler(file_handler)
except Exception as e:
# 文件 handler 创建失败,只输出到控制台
try:
print(f"[日志配置] 警告:无法创建日志文件 {log_file}: {e}")
except Exception:
pass
_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'}"
)
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,
):
"""
参数:
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()
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:
print(f"[日志监控] CRITICAL: {message}")
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:
print(f"[日志监控] WARNING: {message}")
# 检查轮转频率
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 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,
) -> None:
"""启动日志轮转监控器
参数:
logs_dir: 日志目录
base_name: 日志文件基础名称
warning_size_mb: 警告大小阈值(MB)
critical_size_mb: 严重大小阈值(MB)
check_interval: 检查间隔(秒)
alert_callback: 告警回调函数
"""
global _log_monitor
if _log_monitor:
_log_monitor.stop()
_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,
)
_log_monitor.start()
def stop_log_monitor() -> None:
"""停止日志轮转监控器"""
global _log_monitor
if _log_monitor:
_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 _logging_configured:
# 延迟配置,避免在导入时读取 config.json 失败
try:
configure_logging()
except Exception:
pass