优化后台截图功能
This commit is contained in:
1 parent
223c127e11
commit
ace3bbfa04
70 files changed
+4392
-871
No files matched your search
@@ -154,6 +154,38 @@ def find_and_open_fudai_detail(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
|
||||
try:
|
||||
from PIL import Image
|
||||
import path_config
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
img.load()
|
||||
pic_rgb_full = img.convert("RGB")
|
||||
# 使用与检测处相同的命名(pixel_detect + fudai_icon + detected)
|
||||
debug_path = douyin_screenshot_manager.save_debug_image(
|
||||
pic_rgb_full,
|
||||
operation_type="pixel_detect",
|
||||
picname="fudai_icon",
|
||||
step="detected",
|
||||
coords=None,
|
||||
extra_info={"source": "flow_on_detect", "click_x": click_x, "click_y": click_y},
|
||||
)
|
||||
if debug_path:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[调试图像]",
|
||||
"流程检测到福袋图标后保存完整截图",
|
||||
path=debug_path,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
# 不要让调试保存影响主流程
|
||||
pass
|
||||
|
||||
# 优先走底层 operation.click,失败再尝试 analyser.click
|
||||
try:
|
||||
|
||||
@@ -21,7 +21,7 @@ from douyin.stage import douyin_stage
|
||||
from douyin.detection import douyin_detection
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
from douyin.other import douyin_live_room
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.utils import douyin_config
|
||||
@@ -313,6 +313,24 @@ class fudai_analyse:
|
||||
except Exception:
|
||||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||||
|
||||
# 启动后台截图服务(多线程优化)
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
if self.device_id:
|
||||
service.start(self.device_id, interval=1.5)
|
||||
# 验证服务是否启动成功
|
||||
time.sleep(0.1) # 短暂等待
|
||||
if service.is_running():
|
||||
self._log_kv("截图服务", "后台截图服务启动成功", device_id=self.device_id, interval=1.5)
|
||||
else:
|
||||
self._log_kv("截图服务", "后台截图服务启动失败", device_id=self.device_id)
|
||||
else:
|
||||
self._log_kv("截图服务", "设备ID为空,无法启动后台截图服务")
|
||||
except Exception as e:
|
||||
# 服务启动失败不影响主流程,回退到直接截图
|
||||
self._log_kv("截图服务", "后台截图服务启动异常", error=str(e))
|
||||
|
||||
# 记录运行开始
|
||||
from datetime import datetime
|
||||
|
||||
@@ -1231,7 +1249,7 @@ class fudai_analyse:
|
||||
except Exception:
|
||||
pass
|
||||
# 查找福袋并打开详情页
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
|
||||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||||
original_max_wait = getattr(
|
||||
@@ -2054,7 +2072,7 @@ class fudai_analyse:
|
||||
pass
|
||||
|
||||
# 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间)
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
|
||||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||||
# 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds
|
||||
|
||||
@@ -13,7 +13,7 @@ import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from douyin.stage import douyin_stage
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.utils import douyin_helpers
|
||||
from douyin.stage import douyin_stage_handler
|
||||
@@ -57,6 +57,24 @@ class MainFlowController:
|
||||
except Exception:
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400
|
||||
|
||||
# 启动后台截图服务(多线程优化)
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
if analyser.device_id:
|
||||
service.start(analyser.device_id, interval=1.5)
|
||||
# 验证服务是否启动成功
|
||||
time.sleep(0.1) # 短暂等待
|
||||
if service.is_running():
|
||||
analyser._log_kv("截图服务", "后台截图服务启动成功", device_id=analyser.device_id, interval=1.5)
|
||||
else:
|
||||
analyser._log_kv("截图服务", "后台截图服务启动失败", device_id=analyser.device_id)
|
||||
else:
|
||||
analyser._log_kv("截图服务", "设备ID为空,无法启动后台截图服务")
|
||||
except Exception as e:
|
||||
# 服务启动失败不影响主流程,回退到直接截图
|
||||
analyser._log_kv("截图服务", "后台截图服务启动异常", error=str(e))
|
||||
|
||||
# 记录运行开始时间
|
||||
analyser._run_start_ts = time.time()
|
||||
|
||||
|
||||
@@ -105,6 +105,8 @@ class BaseFudaiMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -222,7 +222,7 @@ class MainLogicMixin(BaseFudaiMixin):
|
||||
"""直播间有无福袋的处理逻辑。"""
|
||||
try:
|
||||
# 使用 flow_control 来查找和打开福袋
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||||
|
||||
|
||||
@@ -79,6 +79,8 @@ class RoomUtilsMixin:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"updated_ts": 1767105402.1814883,
|
||||
"updated_ts": 1767151029.2816675,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
|
||||
@@ -51,6 +51,8 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -466,8 +466,9 @@ def check_have_fudai_with_ready_screenshot(
|
||||
import numpy as _np
|
||||
|
||||
# 计算检测区域,考虑分辨率缩放和偏移
|
||||
y0 = 403 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 41 * rx // 1080)
|
||||
# 将像素检测的扫描带左上角改为图片坐标 x=157, y=354(右下不变)
|
||||
y0 = 354 * ry // 2400 + y_pianyi_val
|
||||
x1 = max(0, 157 * rx // 1080)
|
||||
x2 = min(width, 410 * rx // 1080)
|
||||
y_top = max(0, y0 - 3)
|
||||
y_bottom = min(height, y0 + 4)
|
||||
@@ -1237,11 +1238,11 @@ def check_have_fudai_with_ready_screenshot(
|
||||
y_pianyi_val = 0
|
||||
|
||||
# 定义搜索区域(仅在更小的范围内寻找福袋图标)
|
||||
# X范围:160-269(1080基准)
|
||||
# Y范围:348-451(2400基准)
|
||||
search_x1 = max(0, 160 * rx // 1080)
|
||||
# X范围:157-269(1080基准) # 左上角 X 改为图片中的坐标 x=157(右下不变)
|
||||
# Y范围:354-451(2400基准) # 左上角 Y 改为图片中的坐标 y=354(右下不变)
|
||||
search_x1 = max(0, 157 * rx // 1080)
|
||||
search_x2 = min(screenshot_img.shape[1], 269 * rx // 1080)
|
||||
search_y1_base = 348 * ry // 2400 + y_pianyi_val
|
||||
search_y1_base = 354 * ry // 2400 + y_pianyi_val
|
||||
search_y2_base = 451 * ry // 2400 + y_pianyi_val
|
||||
search_y1 = max(0, search_y1_base)
|
||||
search_y2 = min(screenshot_img.shape[0], search_y2_base)
|
||||
|
||||
@@ -92,6 +92,8 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -24,7 +24,21 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
"""获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。"""
|
||||
|
||||
# 检查是否启用调试截图保存(默认False,正常运行时跳过以提升性能)
|
||||
save_debug_images = bool(getattr(analyser, "fudai_detail_save_debug_images", False) or False)
|
||||
try:
|
||||
save_debug_images = bool(getattr(analyser, "fudai_detail_save_debug_images", False))
|
||||
except Exception:
|
||||
save_debug_images = False
|
||||
# 如果analyser未提供配置,回退到全局配置文件
|
||||
if not save_debug_images:
|
||||
try:
|
||||
import json
|
||||
cfg_path = path_config.get_config_path()
|
||||
if os.path.exists(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
save_debug_images = bool(cfg.get("fudai_detail_save_debug_images", False))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _parse_mm_ss(text: str):
|
||||
m = re.search(r"(\d{1,2})[::](\d{2})", str(text or ""))
|
||||
@@ -2877,7 +2891,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
# 尝试重新打开福袋详情页
|
||||
try:
|
||||
# 延迟导入避免循环导入
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
|
||||
room_pos_ref = [0]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(
|
||||
|
||||
@@ -118,7 +118,7 @@ else:
|
||||
# 2. 查找福袋图标并尝试打开
|
||||
analyser._log_kv("流程", "查找福袋图标")
|
||||
try:
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
room_pos_ref = [int(getattr(analyser, "room_pos", 0) or 0)]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(analyser, room_pos_ref)
|
||||
if opened:
|
||||
|
||||
@@ -56,6 +56,8 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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 失败
|
||||
|
||||
@@ -66,6 +66,8 @@ __all__ = [
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -518,7 +518,7 @@ class ReservationHandler:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
|
||||
room_pos_ref = [int(getattr(analyser, "room_pos", 0) or 0)]
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any, Tuple, List, Optional
|
||||
from douyin.stage import douyin_stage
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai import douyin_fudai_core
|
||||
from douyin.core import douyin_flow_control
|
||||
import douyin.core.douyin_flow_control as douyin_flow_control
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
|
||||
|
||||
Reference in new issue
Block a user