优化后台截图功能
This commit is contained in:
1 parent
223c127e11
commit
ace3bbfa04
70 files changed
+4392
-871
No files matched your search
@@ -47,6 +47,8 @@ __all__ = ["track_action"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -5,10 +5,13 @@
|
||||
功能:
|
||||
1. 标准 logging 配置(支持日志轮转、级别管理)
|
||||
2. 按日期分割日志(每天一个新日志文件)
|
||||
3. 自动删除过旧日志(可配置保留天数)
|
||||
4. 增强的日志记录工具(自动记录调用者信息、异常堆栈等)
|
||||
5. 性能监控装饰器(记录函数调用耗时)
|
||||
6. 上下文管理器(记录代码块执行时间)
|
||||
3. 大小限制轮转(防止单个文件过大)
|
||||
4. 自动压缩旧日志文件
|
||||
5. 智能清理策略(大小、数量、时间三重限制)
|
||||
6. 轮转监控和告警
|
||||
7. 增强的日志记录工具(自动记录调用者信息、异常堆栈等)
|
||||
8. 性能监控装饰器(记录函数调用耗时)
|
||||
9. 上下文管理器(记录代码块执行时间)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,6 +24,9 @@ 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
|
||||
@@ -31,30 +37,51 @@ import path_config
|
||||
_logging_configured = False
|
||||
_logger_cache: Dict[str, logging.Logger] = {}
|
||||
|
||||
# 日志监控器实例
|
||||
_log_monitor: Optional['LogRotationMonitor'] = None
|
||||
|
||||
class DatedFileHandler(logging.FileHandler):
|
||||
"""按日期创建日志文件的Handler,每天创建一个新文件"""
|
||||
|
||||
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 = 100 * 1024 * 1024, # 100MB
|
||||
backup_count: int = 10, # 同一日期内最多保留的文件数
|
||||
encoding: str = "utf-8-sig",
|
||||
mode: str = "a",
|
||||
errors: str = "replace",
|
||||
compress_old: bool = True, # 是否压缩旧日志
|
||||
):
|
||||
"""
|
||||
参数:
|
||||
base_filename: 基础文件名(不含日期和扩展名),如 "logs/unified"
|
||||
date_format: 日期格式,默认 "%Y-%m-%d" (例如: 2024-01-15)
|
||||
encoding: 文件编码,默认 "utf-8-sig" (带BOM,避免Windows乱码)
|
||||
mode: 打开模式,默认 "a" (追加)
|
||||
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.current_date = datetime.now().strftime(date_format)
|
||||
self.current_filename = f"{base_filename}_{self.current_date}.log"
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
self.current_sequence = 0 # 当前文件序号
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
@@ -68,30 +95,87 @@ class DatedFileHandler(logging.FileHandler):
|
||||
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 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:
|
||||
"""发送日志记录,如果日期变化则切换到新文件(性能优化版本)"""
|
||||
# 优化:缓存日期检查,避免每次调用都执行 datetime.now().strftime()
|
||||
# 使用记录计数器和时间戳来减少日期检查频率
|
||||
if not hasattr(self, '_date_check_counter'):
|
||||
self._date_check_counter = 0
|
||||
self._last_date_check_time = datetime.now()
|
||||
|
||||
# 每100条记录或每1秒检查一次日期(平衡性能和准确性)
|
||||
"""发送日志记录,支持日期和大小轮转"""
|
||||
# 检查是否需要日期轮转
|
||||
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 today != self.current_date:
|
||||
# 日期变化,关闭旧文件,打开新文件
|
||||
# 日期变化,轮转到新日期
|
||||
self.close()
|
||||
self.current_date = today
|
||||
self.current_filename = f"{self.base_filename}_{self.current_date}.log"
|
||||
self.current_filename = self._get_filename_for_date(self.current_date)
|
||||
|
||||
# 确保目录存在
|
||||
log_dir = os.path.dirname(self.current_filename)
|
||||
@@ -101,74 +185,218 @@ class DatedFileHandler(logging.FileHandler):
|
||||
# 重新初始化文件流
|
||||
self.baseFilename = self.current_filename
|
||||
self.stream = self._open()
|
||||
|
||||
|
||||
# 重置计数器
|
||||
self._date_check_counter = 0
|
||||
|
||||
super().emit(record)
|
||||
|
||||
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 cleanup_old_logs(logs_dir: str, base_name: str, keep_days: int = 30) -> None:
|
||||
"""删除过旧的日志文件
|
||||
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天,超过此天数的日志将被删除
|
||||
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
|
||||
return stats
|
||||
|
||||
# 构建匹配模式,例如: logs/unified_*.log
|
||||
pattern = os.path.join(logs_dir, f"{base_name}_*.log")
|
||||
log_files = glob.glob(pattern)
|
||||
# 收集所有相关日志文件(包括压缩文件)
|
||||
patterns = [
|
||||
os.path.join(logs_dir, f"{base_name}_*.log"),
|
||||
os.path.join(logs_dir, f"{base_name}_*.log.gz"),
|
||||
]
|
||||
|
||||
if not log_files:
|
||||
return
|
||||
all_files = []
|
||||
for pattern in patterns:
|
||||
all_files.extend(glob.glob(pattern))
|
||||
|
||||
cutoff_date = datetime.now() - timedelta(days=keep_days)
|
||||
deleted_count = 0
|
||||
if not all_files:
|
||||
return stats
|
||||
|
||||
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", "")
|
||||
# 按修改时间排序(最新的在前)
|
||||
all_files.sort(key=lambda x: os.path.getmtime(x), 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=lambda x: os.path.getmtime(x))
|
||||
|
||||
for log_file in sorted_files:
|
||||
if total_size <= max_total_size_bytes:
|
||||
break
|
||||
|
||||
# 尝试解析日期
|
||||
try:
|
||||
file_date = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
# 如果日期格式不匹配,尝试其他格式或跳过
|
||||
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
|
||||
|
||||
# 如果文件日期早于截止日期,删除文件
|
||||
if file_date < cutoff_date:
|
||||
os.remove(log_file)
|
||||
deleted_count += 1
|
||||
except Exception as e:
|
||||
# 删除失败时记录但不中断流程
|
||||
# 从文件名提取日期
|
||||
filename = os.path.basename(log_file)
|
||||
# 处理压缩文件扩展名
|
||||
if filename.endswith('.gz'):
|
||||
filename = filename[:-3]
|
||||
|
||||
# 提取日期部分
|
||||
date_part = filename.replace(f"{base_name}_", "").split('.')[0]
|
||||
|
||||
try:
|
||||
print(f"[日志清理] 删除日志文件失败 {log_file}: {e}")
|
||||
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 deleted_count > 0:
|
||||
# 输出统计信息
|
||||
if stats['deleted'] > 0 or stats['compressed'] > 0:
|
||||
try:
|
||||
print(
|
||||
f"[日志清理] 已删除 {deleted_count} 个超过 {keep_days} 天的旧日志文件"
|
||||
)
|
||||
print(f"[日志清理] 完成 - 删除:{stats['deleted']}, 压缩:{stats['compressed']}, "
|
||||
f"释放:{stats['freed_space_mb']:.1f}MB")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
# 清理失败不应影响程序运行
|
||||
try:
|
||||
print(f"[日志清理] 清理旧日志时出错: {e}")
|
||||
print(f"[日志清理] 清理过程出错: {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
"""获取指定名称的 logger,如果未配置则自动配置"""
|
||||
@@ -206,24 +434,36 @@ def get_logger(name: Optional[str] = None) -> logging.Logger:
|
||||
def configure_logging(
|
||||
log_level: Optional[str] = None,
|
||||
log_file: Optional[str] = None,
|
||||
max_bytes: int = 10 * 1024 * 1024, # 10MB (保留作为备用)
|
||||
backup_count: int = 5, # 保留作为备用
|
||||
max_bytes: int = 100 * 1024 * 1024, # 100MB
|
||||
backup_count: int = 10, # 同一日期内保留的文件数
|
||||
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: 单个日志文件最大大小(字节),超过后轮转(仅在不使用日期日志时生效)
|
||||
backup_count: 保留的备份文件数量(仅在不使用日期日志时生效)
|
||||
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
|
||||
|
||||
@@ -251,6 +491,12 @@ def configure_logging(
|
||||
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)
|
||||
except Exception:
|
||||
if log_level is None:
|
||||
log_level = "INFO"
|
||||
@@ -260,6 +506,8 @@ def configure_logging(
|
||||
keep_days = 30
|
||||
if use_dated_logs is None:
|
||||
use_dated_logs = True
|
||||
if compress_logs is None:
|
||||
compress_logs = True
|
||||
|
||||
# 规范化日志级别
|
||||
if log_level is None:
|
||||
@@ -312,13 +560,16 @@ def configure_logging(
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 使用按日期分割的Handler
|
||||
file_handler = DatedFileHandler(
|
||||
# 使用增强的轮转Handler
|
||||
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,
|
||||
)
|
||||
|
||||
# 启动时清理旧日志
|
||||
@@ -326,8 +577,26 @@ def configure_logging(
|
||||
cleanup_old_logs(
|
||||
log_dir or path_config.get_logs_dir(),
|
||||
os.path.basename(base_filename),
|
||||
keep_days,
|
||||
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),
|
||||
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:
|
||||
@@ -574,6 +843,225 @@ def format_exception_info(exc_info=None) -> str:
|
||||
)
|
||||
|
||||
|
||||
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 失败
|
||||
|
||||
Reference in new issue
Block a user