Refactor reservation preemption handling and logging
- Removed the reservation preempt minimum value from the Runner and GUI components. - Updated logging mechanism to streamline log message handling and improve readability. - Introduced a new method for appending log lines in the Runner class. - Cleaned up related GUI elements and configuration options in web interface. - Deleted obsolete simulation scripts related to reservation preemption checks.
This commit is contained in:
1 parent
eb96d6869e
commit
93d47a16d6
20 files changed
+786
-1051
No files matched your search
@@ -593,7 +593,6 @@ python run_cli.py \
|
||||
| `high_value_fudai_after_action` | string | `"continue"` | 完成预约后的动作:`"stay"`=停留,`"continue"`=继续抢福袋 |
|
||||
| `reservation_back_verify_enabled` | boolean | `false` | 是否启用预约回退验证(回退后验证是否在目标直播间) |
|
||||
| `reservation_back_swipe_delay` | float | `0.6` | 预约回退时的滑动延迟(秒) |
|
||||
| `reservation_preempt_min_value` | float | `0.0` | 预约抢占最小价值(元),低于该价值的预约不会抢占当前任务 |
|
||||
|
||||
### 高价值直播间回访
|
||||
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 180,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"reset_after_swipes": 30,
|
||||
"reset_after_swipes_action": "back",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
@@ -21,7 +21,6 @@
|
||||
"high_value_room_revisit_only_current_run": false,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.1,
|
||||
"reservation_preempt_min_value": 0.0,
|
||||
"desktop_icon_x": 153,
|
||||
"desktop_icon_y": 260,
|
||||
"yanghao_fallback_live_x": 540,
|
||||
@@ -154,6 +153,7 @@
|
||||
"debug_detail_level": "minimal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "minimal",
|
||||
"log_format_mode": "simple",
|
||||
"color_output": true,
|
||||
"max_log_lines_display": 1000,
|
||||
"auto_scroll_logs": true,
|
||||
|
||||
+22
-44
@@ -1,15 +1,16 @@
|
||||
# 抖音福袋挂机 — 完整技术文档(重构)
|
||||
|
||||
版本: V4.0
|
||||
最后更新: 2026-01-03
|
||||
版本: V4.1
|
||||
最后更新: 2026-01-07
|
||||
目标读者: 开发者、维护者、运维与 AI 助手
|
||||
|
||||
说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。
|
||||
|
||||
-- 变更记录
|
||||
- 2026-01-07: V4.1 — 删除所有预约抢占逻辑,包括配置项、代码实现和相关文档。
|
||||
- 2026-01-03: V4.0 — 重构文档结构,补充快速上手、配置优先级、截图/OCR/日志说明、故障排查与验证清单。
|
||||
|
||||
## 最近修复与配置变更(2026-01-03)
|
||||
## 最近修复与配置变更(2026-01-07)
|
||||
|
||||
本小节记录最近完成的若干修复与功能开关,便于开发与运维快速验证和回滚。
|
||||
|
||||
@@ -30,26 +31,21 @@
|
||||
- 日志写法修正:将 ad-hoc 的直接写 actions.log 的行为替换为通过统一 logger 输出,避免 RotatingFileHandler 在 Windows 上轮转时报 WinError 32(文件被占用)。相关调整见 `douyin/handlers/douyin_screenshot_manager.py` / `douyin/logging/*`。
|
||||
|
||||
- 验证要点(运行时观察):
|
||||
- 当 `fudai_disable_content_recognition` 为 true 时,日志中应出现至少一条:
|
||||
- `跳过福袋内容OCR识别(配置启用)` 或 `跳过备用福袋内容OCR识别(配置启用)` 或 `跳过串行福袋内容OCR识别(配置启用)`。
|
||||
- 并且不会出现新的 `OCR识别福袋内容` 的性能/计时条目(即不再有与 content OCR 相关的耗时统计)。
|
||||
- 当 `fudai_disable_task_recognition` 为 true 时,日志中应出现:
|
||||
- `跳过福袋任务列表OCR识别(配置启用)`,并且不会有任务列表 OCR 的原始输出条目。
|
||||
- 连续未找到福袋触发退出:将 `fudai_exit_after_misses` 设为小值(例如 3),运行短会话,日志应出现类似:
|
||||
- `连续未找到福袋达到阈值:按返回键退出直播间`(或相近日志),并能在 `logs/actions.log` 中看到对应的返回按键事件。
|
||||
- actions.log 轮转问题:在长时间运行后触发日志轮转,确认不会再出现 Windows 的 `PermissionError` / `WinError 32` 异常。
|
||||
- 预约系统不再执行抢占行为,日志中不会出现抢占相关的处理信息
|
||||
- 配置文件中不再包含抢占相关配置项
|
||||
- 代码中不再有抢占逻辑的分支判断
|
||||
|
||||
- 快速验证命令(仓库根目录,PowerShell):
|
||||
|
||||
```powershell
|
||||
# 语法检查
|
||||
python -m py_compile douyin/fudai/core/fudai_detail_reader.py
|
||||
python -m py_compile douyin/core/douyin_fudai.py
|
||||
|
||||
# 在 config 里临时启用开关(手动修改 config/config.json)后运行一次短会话
|
||||
# 运行短会话验证预约功能正常
|
||||
python run_cli.py --wait-minutes 0 --device-id <ADB_ID>
|
||||
|
||||
# 在日志中查找跳过消息(示例)
|
||||
Select-String -Path logs\*.log -Pattern "跳过福袋内容OCR识别|跳过福袋任务列表OCR识别|连续未找到福袋"
|
||||
# 检查配置文件中是否删除了抢占相关配置项
|
||||
Select-String -Path config/config.json -Pattern "preempt|poll_before"
|
||||
```
|
||||
|
||||
如果需要,我可以把这些验证步骤写成一键脚本 `tools/verify_fudai_disable.sh` / `tools/verify_fudai_disable.ps1` 以便 CI 调用。
|
||||
@@ -411,7 +407,7 @@ run_once_basic(recursion_depth=0)
|
||||
└─> 如需回退则在回退流程中直接处理参与逻辑(不再使用 `_reservation_back_direct_attend` 或 `_force_attend_after_reservation_back` 标志)
|
||||
↓
|
||||
[检查2] 等待开奖状态 (_waiting_for_lottery_result)
|
||||
├─> 是 → 检查预约抢占 → 检查开奖结果 → return
|
||||
├─> 是 → 检查开奖结果 → return
|
||||
└─> 否 → 继续
|
||||
↓
|
||||
[检查3] 30分钟超时检查
|
||||
@@ -721,10 +717,7 @@ def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0,
|
||||
|
||||
**0. 检查等待开奖状态** (`_waiting_for_lottery_result`)
|
||||
- 如果为 `True`,执行以下逻辑:
|
||||
1. **检查预约抢占**:
|
||||
- 如果启用高价值预约且预约队列不为空,调用 `process_reservation_attend_window()` 检查是否需要抢占
|
||||
- 如果检测到预约需要处理,清除等待开奖标志,中断等待,继续执行后续逻辑
|
||||
2. **等待开奖时间检查**:
|
||||
1. **等待开奖时间检查**:
|
||||
- 计算剩余秒数:`remain_seconds = max(0, future_ts - current_ts + 6.0)`(加上6秒延迟修正)
|
||||
- 开奖检测开始时间:`check_start_ts = future_ts + 1.0`(开奖时间+1秒缓冲)
|
||||
- 超时时间:`timeout_ts = future_ts + 10.0`(超过开奖时间10秒清除等待标志)
|
||||
@@ -787,14 +780,7 @@ def run_once_basic(self) -> None:
|
||||
|
||||
# 0. 检查等待开奖状态
|
||||
if getattr(self, "_waiting_for_lottery_result", False):
|
||||
# 检查预约抢占
|
||||
if high_value_enabled and reservations:
|
||||
preempted = process_reservation_attend_window(...)
|
||||
if preempted:
|
||||
self._waiting_for_lottery_result = False
|
||||
# 继续执行后续逻辑
|
||||
else:
|
||||
# 等待开奖时间检查
|
||||
# 等待开奖时间检查
|
||||
remain_seconds = max(0, future_ts - current_ts + 6.0)
|
||||
check_start_ts = future_ts + 1.0
|
||||
timeout_ts = future_ts + 10.0
|
||||
@@ -2785,8 +2771,7 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
"high_value_room_revisit_enabled": true, // 是否启用高价值直播间重访
|
||||
"high_value_room_revisit_only_current_run": true, // 是否仅在当前运行中重访
|
||||
"reservation_back_verify_enabled": true, // 是否验证预约回退
|
||||
"reservation_back_swipe_delay": 0.1, // 预约回退滑动延迟(秒)
|
||||
"reservation_preempt_min_value": 0.0 // 预约抢占最小价值(元)
|
||||
"reservation_back_swipe_delay": 0.1 // 预约回退滑动延迟(秒)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -2802,7 +2787,6 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
- **`high_value_room_revisit_only_current_run`**: 是否仅在当前运行中重访(重启后不保留)
|
||||
- **`reservation_back_verify_enabled`**: 是否验证预约回退(回退后验证是否在目标直播间)
|
||||
- **`reservation_back_swipe_delay`**: 预约回退滑动后的延迟(秒)
|
||||
- **`reservation_preempt_min_value`**: 预约抢占最小价值(如果新福袋价值更高,可以抢占旧预约)
|
||||
|
||||
#### 7.2.4 福袋查找配置
|
||||
|
||||
@@ -3038,16 +3022,11 @@ if self._reservation_back_direct_attend:
|
||||
```python
|
||||
# 在 run_once_basic() 中
|
||||
if self._waiting_for_lottery_result:
|
||||
# 检查预约抢占
|
||||
if self._check_reservation_preempt():
|
||||
self._waiting_for_lottery_result = False
|
||||
return
|
||||
|
||||
# 检查开奖结果
|
||||
if time.time() >= self._lottery_result_expected_ts:
|
||||
self._handle_lottery_result()
|
||||
self._waiting_for_lottery_result = False
|
||||
return
|
||||
# 检查开奖结果
|
||||
if time.time() >= self._lottery_result_expected_ts:
|
||||
self._handle_lottery_result()
|
||||
self._waiting_for_lottery_result = False
|
||||
return
|
||||
```
|
||||
|
||||
#### 8.2.3 跳过阶段诊断标志
|
||||
@@ -3188,9 +3167,8 @@ def save_reservations_to_state(analyser):
|
||||
|
||||
1. **设置等待状态**: 参与福袋后,如果倒计时较长(> 30秒),设置等待状态
|
||||
2. **等待期间**: 继续运行主循环,但跳过福袋查找和参与
|
||||
3. **检查预约抢占**: 如果发现更高价值的预约,取消当前等待
|
||||
4. **检查开奖结果**: 到达预期开奖时间后,检查开奖结果
|
||||
5. **清除等待状态**: 处理完开奖结果后清除
|
||||
3. **检查开奖结果**: 到达预期开奖时间后,检查开奖结果
|
||||
4. **清除等待状态**: 处理完开奖结果后清除
|
||||
|
||||
**代码示例**:
|
||||
```python
|
||||
|
||||
@@ -206,10 +206,6 @@ class fudai_analyse:
|
||||
self.reservation_back_verify_enabled: bool = True # 默认启用回退校验
|
||||
# 未做回退校验时的快速回滑延迟(秒)
|
||||
self.reservation_back_swipe_delay: float = 0.6
|
||||
# 预约抢占最小价值:低于该价值的预约不会抢占当前任务(元)
|
||||
self.reservation_preempt_min_value_yuan: float = 0.0
|
||||
# 在预计开奖前多少秒开始积极轮询结果
|
||||
self.poll_before_open_seconds: int = 10
|
||||
|
||||
# 滑动次数重置相关
|
||||
self.reset_after_swipes_enabled: bool = False # 由 Web/CLI 显式开关
|
||||
@@ -1745,53 +1741,7 @@ class fudai_analyse:
|
||||
after_action_ref[0]
|
||||
)
|
||||
|
||||
if preempted:
|
||||
# 已触发预约回退:走标准回退处理流程(不使用已移除的直接参与标志)
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约回退成功:进入回退处理(直接参与标志已移除)",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 关键修复:不再在这里直接 return。
|
||||
# 否则会在锁定期内每轮都被 preempted 拦截,导致“回退成功”日志反复出现,
|
||||
# 但永远不进入后续的直播间识别/参与逻辑,用户观感为卡死。
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退完成:继续处理当前直播间(识别详情/参与),锁定期内不切房",
|
||||
focus_until=float(
|
||||
getattr(self, "reservation_focus_until_ts", 0.0)
|
||||
or 0.0
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 在回退后尝试立即推进一次识别/参与流程,避免依赖下一轮循环。
|
||||
# 仅在当前不处于等待开奖状态时执行(避免打断等待流程)。
|
||||
try:
|
||||
if not getattr(self, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退后立即尝试处理当前直播间以推进识别/参与",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._handle_live_room_has_or_not_fudai()
|
||||
except Exception as e:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退后立即处理当前直播间出错",
|
||||
error=str(e),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
# 抢占逻辑已删除,直接继续处理
|
||||
else:
|
||||
# 单间模式:不需要回退,预约会在当前直播间自动识别和参与
|
||||
# 只需要清理过期的预约
|
||||
@@ -3335,9 +3285,6 @@ class fudai_analyse:
|
||||
)
|
||||
or 120
|
||||
)
|
||||
# poll_before = float(
|
||||
# getattr(self, "poll_before_open_seconds", 10.0) or 10.0
|
||||
# ) # 未使用,注释掉
|
||||
time_window_start_ts = ft - join_ahead
|
||||
|
||||
# 如果时间窗口未到,避免重复打开福袋详情
|
||||
|
||||
@@ -5001,14 +5001,6 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
# 未命中黑名单,继续记录预约
|
||||
try:
|
||||
# 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务)
|
||||
try:
|
||||
preempt_min = float(
|
||||
getattr(analyser, "reservation_preempt_min_value_yuan", 0.0)
|
||||
or 0.0
|
||||
)
|
||||
except Exception:
|
||||
preempt_min = 0.0
|
||||
|
||||
# 初始化预约队列容器
|
||||
reservations = getattr(analyser, "reservations", None)
|
||||
if reservations is None:
|
||||
@@ -5424,7 +5416,6 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
future_ts=int(future_ts),
|
||||
room_pos=room_pos,
|
||||
queue_len=len(reservations),
|
||||
preempt_min_value=preempt_min,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -643,13 +643,13 @@ def configure_logging(
|
||||
# 清除已有的 handlers(避免重复配置)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
# 统一日志格式:时间戳(毫秒) - [级别] - [线程名] - [模块名:函数名:行号] - [traceId] - 消息
|
||||
# 简化的日志格式:时间戳 - [级别] - [模块] - 消息
|
||||
# 去掉了冗余的线程名、函数名、行号、traceId等信息,使日志更简洁
|
||||
detailed_format = (
|
||||
"%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - "
|
||||
"[%(name)s:%(funcName)s:%(lineno)d] - [traceId:%(traceId)s] - %(message)s"
|
||||
"%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s"
|
||||
)
|
||||
simple_format = (
|
||||
"%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - %(message)s"
|
||||
"%(asctime)s - [%(levelname)s] - %(message)s"
|
||||
)
|
||||
|
||||
# 控制台输出
|
||||
@@ -660,6 +660,12 @@ def configure_logging(
|
||||
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)
|
||||
|
||||
# 文件输出(按日期分割或传统轮转)
|
||||
@@ -826,6 +832,12 @@ def configure_logging(
|
||||
)
|
||||
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 创建失败,只输出到控制台
|
||||
|
||||
@@ -210,450 +210,163 @@ class LoggingWrapper:
|
||||
"back_times": "需回退次数",
|
||||
}
|
||||
|
||||
# 构建日志行(增强格式:时间 级别 标签 [调用者] 消息 字段...)
|
||||
# 构建简洁的日志行:时间 [级别] [标签] 消息 关键字段
|
||||
log_parts: list[str] = []
|
||||
if timestamp:
|
||||
log_parts.append(f"[{timestamp}]")
|
||||
log_parts.append(f"[{log_level}]")
|
||||
log_parts.append(f"[{tag}]")
|
||||
# 如果有 log_type,则在可读日志中加入类型标记,方便过滤与配色
|
||||
if log_type:
|
||||
log_parts.append(f"[{log_type}]")
|
||||
|
||||
# 添加调用者信息(如果获取成功)
|
||||
if caller_info:
|
||||
log_parts.append(f"[{caller_info}]")
|
||||
if tag and tag != "日志":
|
||||
log_parts.append(f"[{tag}]")
|
||||
|
||||
if msg:
|
||||
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(m) > 200:
|
||||
m = m[:200] + "..."
|
||||
if len(m) > 150:
|
||||
m = m[:150] + "..."
|
||||
log_parts.append(m)
|
||||
|
||||
# 添加字段信息
|
||||
# 只添加最重要的字段,避免日志过长
|
||||
important_fields = []
|
||||
for k, v in fields.items():
|
||||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||||
continue
|
||||
if v is None:
|
||||
continue
|
||||
key_cn = key_map.get(str(k), f"字段_{k}")
|
||||
# 格式化值
|
||||
if isinstance(v, float):
|
||||
if abs(v) < 1:
|
||||
v_str = f"{v:.3f}"
|
||||
elif abs(v) < 100:
|
||||
v_str = f"{v:.2f}"
|
||||
# 只显示关键字段:耗时、价值、错误等
|
||||
if k in ("elapsed_seconds", "value_yuan", "error", "room_pos", "future_ts"):
|
||||
key_cn = key_map.get(str(k), k)
|
||||
if isinstance(v, float):
|
||||
if "seconds" in k or "elapsed" in k:
|
||||
v_str = f"{v:.1f}s"
|
||||
elif "yuan" in k:
|
||||
v_str = f"{v:.0f}元"
|
||||
else:
|
||||
v_str = f"{v:.1f}"
|
||||
else:
|
||||
v_str = f"{int(v)}"
|
||||
elif isinstance(v, (int, bool)):
|
||||
v_str = str(v)
|
||||
else:
|
||||
s = str(v).replace("\r", " ").replace("\n", " ").strip()
|
||||
if len(s) > 100:
|
||||
s = s[:100] + "..."
|
||||
v_str = s
|
||||
log_parts.append(f"{key_cn}={v_str}")
|
||||
v_str = str(v)[:20] # 限制字段值长度
|
||||
important_fields.append(f"{key_cn}={v_str}")
|
||||
|
||||
if important_fields:
|
||||
log_parts.append(" ".join(important_fields))
|
||||
|
||||
# 构建完整日志行
|
||||
log_line = " ".join(log_parts)
|
||||
|
||||
# 判断是否需要添加分隔符(便于查看日志)
|
||||
# 简化分隔符逻辑,只在真正重要的阶段变化时添加,且使用更简洁的分隔符
|
||||
need_separator = False
|
||||
separator_reason = ""
|
||||
last_tag = getattr(analyser, "_last_log_tag", None)
|
||||
tag_changed = bool(tag) and tag != last_tag
|
||||
|
||||
# 1. 错误发生时(优先级最高)
|
||||
if log_level in ("ERROR", "WARNING", "CRITICAL"):
|
||||
# 只在错误或非常重要的阶段变化时添加分隔符,避免日志过于冗余
|
||||
if log_level in ("ERROR", "CRITICAL"):
|
||||
need_separator = True
|
||||
separator_reason = "错误/警告"
|
||||
|
||||
# 2. 运行开始时
|
||||
elif tag and any(
|
||||
keyword in str(tag) for keyword in ["运行", "启动", "开始", "初始化"]
|
||||
):
|
||||
separator_reason = f"错误: {tag or '系统'}"
|
||||
elif tag_changed and tag in ("运行", "启动", "完成"):
|
||||
need_separator = True
|
||||
separator_reason = "运行开始"
|
||||
separator_reason = tag
|
||||
|
||||
# 3. 阶段变化时(tag变化且包含阶段相关关键词)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["阶段", "循环", "参与", "检测", "寻找", "进入", "退出"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "阶段变化"
|
||||
|
||||
# 4. 重要操作(通过tag判断)
|
||||
elif tag and getattr(analyser, "_last_log_tag", None) != tag:
|
||||
if any(
|
||||
keyword in str(tag)
|
||||
for keyword in ["参与", "中奖", "完成", "失败", "超时"]
|
||||
):
|
||||
need_separator = True
|
||||
separator_reason = "重要操作"
|
||||
|
||||
# 输出分隔符(如果需要)
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
# 使用等号作为分隔符,更清晰易读
|
||||
separator = "=" * 80
|
||||
# 在分隔符中间显示原因,更美观
|
||||
reason_text = f" {separator_reason} "
|
||||
separator_line = (
|
||||
f"{separator}\n{reason_text.center(80, '=')}\n{separator}"
|
||||
)
|
||||
print(separator_line, flush=True)
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 获取日志格式模式配置(simple 或 detailed)
|
||||
log_format_mode = "simple" # 默认简洁模式
|
||||
try:
|
||||
import path_config
|
||||
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)
|
||||
log_format_mode = config.get("logging", {}).get("log_format_mode", "simple")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 根据模式决定日志格式
|
||||
if log_format_mode == "detailed":
|
||||
# 详细模式:保留之前的复杂格式
|
||||
return LoggingWrapper._enhanced_log_kv_detailed(analyser, tag, msg, log_level, log_type, log_parts, timestamp, caller_info, fields, need_separator, separator_reason)
|
||||
else:
|
||||
# 简洁模式:使用优化后的格式
|
||||
return LoggingWrapper._enhanced_log_kv_simple(analyser, tag, msg, log_level, log_parts, timestamp, fields, need_separator, separator_reason)
|
||||
|
||||
@staticmethod
|
||||
def _enhanced_log_kv_simple(analyser: Any, tag: str, msg: str, log_level: str, log_parts: list[str], timestamp: str, fields: Dict[str, Any], need_separator: bool, separator_reason: str) -> None:
|
||||
"""简洁模式的日志记录"""
|
||||
# 输出分隔符(如果需要)- 使用更简洁的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = f"=== {separator_reason} ==="
|
||||
print(separator, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 构建简洁的日志行
|
||||
log_line = " ".join(log_parts)
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
|
||||
try:
|
||||
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 写入行为日志(actions.log)- 使用运行日志格式,但只保留关键信息
|
||||
# 记录所有操作到行为日志
|
||||
# 简化行为日志记录,避免重复输出
|
||||
try:
|
||||
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
|
||||
should_log = True
|
||||
# 只在重要事件时写入行为日志
|
||||
should_log_action = False
|
||||
if tag and any(keyword in str(tag) for keyword in ["参与", "中奖", "完成", "失败", "运行"]):
|
||||
should_log_action = True
|
||||
|
||||
# 过滤一些不需要记录的日志(避免噪音)
|
||||
if tag:
|
||||
# 跳过一些调试或详细日志
|
||||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||||
for skip_tag in skip_tags:
|
||||
if tag.startswith(skip_tag):
|
||||
should_log = False
|
||||
break
|
||||
|
||||
if should_log:
|
||||
if should_log_action:
|
||||
# 获取时间戳
|
||||
if not timestamp:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||||
|
||||
# 提取关键信息:做了什么、耗时、分数
|
||||
# 如果msg为空,从tag中提取操作描述
|
||||
if msg:
|
||||
action_desc = str(msg)
|
||||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||||
# 先移除带冒号的函数名
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||||
)
|
||||
# 再移除带空格的函数名(但后面不是字母/下划线开头的单词)
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||||
)
|
||||
# 如果移除后为空,保留原描述
|
||||
if not action_desc.strip():
|
||||
action_desc = str(msg)
|
||||
# 简化描述:移除字段前缀,只保留关键信息
|
||||
if "字段_" in action_desc:
|
||||
# 提取阶段信息(如果有)
|
||||
if "字段_阶段=" in action_desc:
|
||||
stage_match = re.search(r"字段_阶段=(\w+)", action_desc)
|
||||
if stage_match:
|
||||
action_desc = f"阶段={stage_match.group(1)}"
|
||||
else:
|
||||
# 简化其他字段描述,只保留消息部分
|
||||
action_desc = action_desc.split("字段_")[0].strip()
|
||||
else:
|
||||
# 从tag中提取操作类型(移除标签的方括号)
|
||||
if tag:
|
||||
tag_clean = tag.strip("[]").strip()
|
||||
if tag_clean:
|
||||
action_desc = tag_clean
|
||||
else:
|
||||
action_desc = "操作"
|
||||
else:
|
||||
action_desc = "操作"
|
||||
|
||||
# 归一化字段名,支持以 '字段_' 前缀的字段名向后兼容
|
||||
fields_clean: Dict[str, Any] = {}
|
||||
for k, v in fields.items():
|
||||
kk = str(k)
|
||||
if kk.startswith("字段_"):
|
||||
kk = kk[len("字段_") :]
|
||||
fields_clean[kk] = v
|
||||
|
||||
# 提取耗时(从字段中查找,优先使用毫秒字段)
|
||||
elapsed_str = ""
|
||||
if "elapsed_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "total_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "total_elapsed_ms" in fields_clean:
|
||||
elapsed_seconds = (
|
||||
float(fields_clean.get("total_elapsed_ms", 0)) / 1000.0
|
||||
)
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "总耗时毫秒" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("总耗时毫秒", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "elapsed_seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
|
||||
# 提取分数(如果有)
|
||||
score_str = ""
|
||||
if "score" in fields_clean and fields_clean.get("score") is not None:
|
||||
try:
|
||||
score_val = float(fields_clean.get("score", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
elif (
|
||||
"max_val" in fields_clean
|
||||
and fields_clean.get("max_val") is not None
|
||||
):
|
||||
try:
|
||||
score_val = float(fields_clean.get("max_val", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
elif "分数" in fields_clean:
|
||||
score_field = fields_clean.get("分数")
|
||||
# 允许显示0.0分数,只要不是None
|
||||
if score_field is not None:
|
||||
try:
|
||||
score_val = float(score_field)
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
|
||||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||||
# 构建简洁的行为日志
|
||||
action_parts = [f"[{timestamp}]"]
|
||||
if tag:
|
||||
action_parts.append(tag)
|
||||
else:
|
||||
action_parts.append("[日志]")
|
||||
|
||||
# 在行为日志中也写入类型标签,便于按类型过滤(例如 ERR/DEBUG/SCREENSHOT/PERF/OP)
|
||||
if log_type:
|
||||
action_parts.append(f"[{log_type}]")
|
||||
|
||||
action_parts.append(action_desc)
|
||||
|
||||
if elapsed_str:
|
||||
action_parts.append(elapsed_str)
|
||||
|
||||
if score_str:
|
||||
action_parts.append(score_str)
|
||||
|
||||
action_parts.append(f"[{tag}]")
|
||||
if msg:
|
||||
action_parts.append(msg[:100]) # 限制长度
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
# 使用统一的路径配置
|
||||
try:
|
||||
import path_config
|
||||
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 检测标签变化,并写入行为日志(始终写入,首次也会写)
|
||||
if not hasattr(analyser, "_last_action_tag"):
|
||||
analyser._last_action_tag = None
|
||||
|
||||
current_tag = tag or "[日志]"
|
||||
try:
|
||||
import logging
|
||||
|
||||
action_logger = logging.getLogger("action_logger")
|
||||
# 如果标签变化,先写分隔符
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
action_logger.info("=" * 80)
|
||||
|
||||
# 始终写入精简行为日志行到 action_logger(由 RotatingFileHandler 管理)
|
||||
action_logger.info(action_log_line)
|
||||
analyser._last_action_tag = current_tag
|
||||
except Exception:
|
||||
# 回退到直接写文件(兼容场景)
|
||||
if log_dir:
|
||||
with open(
|
||||
actions_log_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
) as f:
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
f.write("=" * 80 + "\n")
|
||||
analyser._last_action_tag = current_tag
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
with open(
|
||||
actions_log_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
) as f:
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 同时输出到标准 logging(如果已配置,可选)
|
||||
try:
|
||||
# 确保日志系统已配置
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
# 如果根 logger 没有 handlers,尝试配置日志系统
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not hasattr(analyser, "_std_logger") or analyser._std_logger is None:
|
||||
try:
|
||||
from unified_logger import get_unified_logger
|
||||
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
from douyin.logging import douyin_logger
|
||||
|
||||
analyser._std_logger = douyin_logger.get_logger("douyin")
|
||||
except Exception:
|
||||
# 如果都失败了,使用根 logger
|
||||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||||
|
||||
# 使用根 logger 确保日志能写入文件(子 logger 会传播到根 logger)
|
||||
root_logger = logging.getLogger()
|
||||
if root_logger.handlers:
|
||||
# 如果根 logger 有 handlers,使用根 logger 写入(确保能写入文件)
|
||||
# 构建标准 logging 消息(包含调用者信息)
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
# 对消息进行敏感信息脱敏
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||||
std_msg_parts.append(masked_msg)
|
||||
except ImportError:
|
||||
std_msg_parts.append(str(msg))
|
||||
|
||||
# 对字段进行敏感信息脱敏
|
||||
masked_fields: Dict[str, Any] = {}
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
|
||||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||||
except ImportError:
|
||||
masked_fields = fields
|
||||
|
||||
for k, v in masked_fields.items():
|
||||
if k in (
|
||||
"tag",
|
||||
"msg",
|
||||
"level",
|
||||
"exc_info",
|
||||
"_show_caller",
|
||||
"_caller",
|
||||
):
|
||||
continue
|
||||
if v is not None:
|
||||
std_msg_parts.append(f"{k}={v}")
|
||||
|
||||
log_message = " ".join(std_msg_parts)
|
||||
|
||||
# 检查是否有异常信息
|
||||
exc_info = fields.get("exc_info")
|
||||
if exc_info is None:
|
||||
if sys.exc_info()[0] is not None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
# 记录到根 logger(确保能写入文件)
|
||||
# 优化:只写入文件,不输出到控制台(避免与 print 重复)
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
# 临时禁用控制台输出,只写入文件
|
||||
console_handlers = [
|
||||
h
|
||||
for h in root_logger.handlers
|
||||
if isinstance(h, logging.StreamHandler) and h.stream == sys.stdout
|
||||
]
|
||||
# 保存原始级别并在 finally 中恢复,确保在异常路径也能正确还原
|
||||
original_levels = {}
|
||||
for handler in console_handlers:
|
||||
try:
|
||||
original_levels[id(handler)] = getattr(
|
||||
handler, "level", logging.NOTSET
|
||||
)
|
||||
handler.setLevel(logging.CRITICAL + 1) # 临时禁用
|
||||
except Exception:
|
||||
# 如果无法修改某个 handler,跳过但继续记录
|
||||
continue
|
||||
|
||||
try:
|
||||
if exc_info:
|
||||
root_logger.log(
|
||||
level,
|
||||
log_message,
|
||||
exc_info=exc_info,
|
||||
extra={"caller": caller_info},
|
||||
)
|
||||
else:
|
||||
root_logger.log(
|
||||
level, log_message, extra={"caller": caller_info}
|
||||
)
|
||||
finally:
|
||||
# 恢复控制台输出级别到原始值,避免长期禁用
|
||||
for handler in console_handlers:
|
||||
try:
|
||||
orig = original_levels.get(id(handler), logging.NOTSET)
|
||||
handler.setLevel(orig)
|
||||
except Exception:
|
||||
try:
|
||||
handler.setLevel(logging.NOTSET)
|
||||
except Exception:
|
||||
pass
|
||||
elif hasattr(analyser, "_std_logger") and analyser._std_logger:
|
||||
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
|
||||
# 优化:跳过标准 logging 输出,避免与控制台 print 重复
|
||||
# 因为 print 已经输出了,这里只用于文件日志(如果需要)
|
||||
pass # 不再输出到标准 logging,避免重复
|
||||
except Exception as e:
|
||||
# 如果标准 logging 写入失败,记录详细错误信息并尝试使用根 logger 写入(作为备用)
|
||||
try:
|
||||
if _error_logger:
|
||||
_error_logger.log_exception(
|
||||
e, context={"tag": tag, "caller": caller_info}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果标准 logging 写入失败,继续使用根 logger 写入(作为备用)
|
||||
try:
|
||||
import logging
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
# 构建简单的日志消息
|
||||
simple_msg = f"[{tag}] {msg}" if msg else f"[{tag}]"
|
||||
# 直接使用根 logger,它会自动处理子 logger 的传播
|
||||
root_logger.log(level, simple_msg)
|
||||
except Exception:
|
||||
# 如果所有日志写入都失败,至少确保 stdout 输出(已在上面完成)
|
||||
pass
|
||||
# 移除标准 logging 输出,避免与 stdout 重复
|
||||
# 现在只通过 print 输出到控制台,行为日志只记录重要事件
|
||||
|
||||
# 如果有异常堆栈,也输出到 stdout
|
||||
exc_info = fields.get("exc_info")
|
||||
@@ -815,3 +528,296 @@ class LoggingWrapper:
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def _enhanced_log_kv_detailed(analyser: Any, tag: str, msg: str, log_level: str, log_type: str, log_parts: list[str], timestamp: str, caller_info: str, fields: Dict[str, Any], need_separator: bool, separator_reason: str) -> None:
|
||||
"""详细模式的日志记录(保留之前的复杂格式用于debug)"""
|
||||
# 字段映射(中文 key)- 在详细模式中重新定义
|
||||
key_map: Dict[str, str] = {
|
||||
"rid": "运行",
|
||||
"seq": "序号",
|
||||
"msg": "说明",
|
||||
"stage": "阶段",
|
||||
"seen": "识别",
|
||||
"ok": "成功",
|
||||
"text": "文本",
|
||||
"action": "动作",
|
||||
"result": "结果",
|
||||
"mode": "模式",
|
||||
"reason": "原因",
|
||||
"wait_seconds": "等待秒",
|
||||
"value_yuan": "价值元",
|
||||
"future": "开奖时间",
|
||||
"pos_seen": "发现位置",
|
||||
"qsize": "队列数量",
|
||||
"room_pos": "当前位置",
|
||||
"content": "内容",
|
||||
"countdown": "倒计时",
|
||||
"participants": "参与人数",
|
||||
"copies": "份数",
|
||||
"seconds": "耗时秒",
|
||||
"error": "错误",
|
||||
"error_type": "错误类型",
|
||||
"fudai_x": "福袋X坐标",
|
||||
"attempt": "尝试次数",
|
||||
"room_title": "直播间名",
|
||||
"back_times": "需回退次数",
|
||||
}
|
||||
# 输出分隔符(如果需要)- 详细模式使用更明显的分隔符
|
||||
if need_separator:
|
||||
try:
|
||||
separator = "=" * 50
|
||||
separator_line = f"{separator} {separator_reason} {separator}"
|
||||
print(separator_line, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 更新上一个日志标签
|
||||
analyser._last_log_tag = tag
|
||||
|
||||
# 构建详细的日志行(包含更多信息)
|
||||
detailed_log_parts = log_parts.copy()
|
||||
|
||||
# 在详细模式下添加更多字段信息
|
||||
important_fields = []
|
||||
for k, v in fields.items():
|
||||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||||
continue
|
||||
if v is None:
|
||||
continue
|
||||
# 详细模式显示更多字段
|
||||
key_cn = key_map.get(str(k), k)
|
||||
if isinstance(v, float):
|
||||
if "seconds" in k or "elapsed" in k:
|
||||
v_str = f"{v:.2f}s"
|
||||
elif "yuan" in k:
|
||||
v_str = f"{v:.0f}元"
|
||||
else:
|
||||
v_str = f"{v:.2f}"
|
||||
else:
|
||||
v_str = str(v)[:30] # 详细模式允许稍长
|
||||
important_fields.append(f"{key_cn}={v_str}")
|
||||
|
||||
if important_fields:
|
||||
detailed_log_parts.append(" ".join(important_fields))
|
||||
|
||||
# 添加调用者信息(详细模式)
|
||||
if caller_info:
|
||||
detailed_log_parts.append(f"[调用:{caller_info}]")
|
||||
|
||||
log_line = " ".join(detailed_log_parts)
|
||||
|
||||
# 始终输出到 stdout(供 GUI 捕获)
|
||||
try:
|
||||
print(log_line, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 详细的行为日志记录(保留之前的复杂逻辑)
|
||||
try:
|
||||
# 记录所有操作到行为日志(详细模式)
|
||||
should_log = True
|
||||
|
||||
# 过滤一些不需要记录的日志(避免噪音)
|
||||
if tag:
|
||||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||||
for skip_tag in skip_tags:
|
||||
if tag.startswith(skip_tag):
|
||||
should_log = False
|
||||
break
|
||||
|
||||
if should_log:
|
||||
# 提取关键信息:做了什么、耗时、分数
|
||||
def _shorten(value: Any, max_len: int = 60) -> str:
|
||||
s = str(value).strip()
|
||||
if len(s) > max_len:
|
||||
return s[: max_len - 3] + "..."
|
||||
return s
|
||||
|
||||
if msg:
|
||||
action_desc = _shorten(str(msg), max_len=120)
|
||||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||||
)
|
||||
action_desc = re.sub(
|
||||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||||
)
|
||||
if not action_desc.strip():
|
||||
action_desc = _shorten(str(msg), max_len=120)
|
||||
else:
|
||||
if tag:
|
||||
tag_clean = tag.strip("[]").strip()
|
||||
if tag_clean:
|
||||
action_desc = tag_clean
|
||||
else:
|
||||
action_desc = "操作"
|
||||
else:
|
||||
action_desc = "操作"
|
||||
|
||||
# 提取耗时
|
||||
elapsed_str = ""
|
||||
fields_clean: Dict[str, Any] = {}
|
||||
for k, v in fields.items():
|
||||
kk = str(k)
|
||||
if kk.startswith("字段_"):
|
||||
kk = kk[len("字段_") :]
|
||||
fields_clean[kk] = v
|
||||
|
||||
if "elapsed_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "total_ms" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("total_ms", 0)) / 1000.0
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
elif "elapsed_seconds" in fields_clean:
|
||||
elapsed_seconds = float(fields_clean.get("elapsed_seconds", 0))
|
||||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||||
|
||||
# 提取分数
|
||||
score_str = ""
|
||||
if "score" in fields_clean and fields_clean.get("score") is not None:
|
||||
try:
|
||||
score_val = float(fields_clean.get("score", 0))
|
||||
score_str = f"分数:{score_val:.3f}"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 构建详细的行为日志行
|
||||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||||
if tag:
|
||||
action_parts.append(tag)
|
||||
else:
|
||||
action_parts.append("[日志]")
|
||||
|
||||
if log_type:
|
||||
action_parts.append(f"[{log_type}]")
|
||||
|
||||
action_parts.append(action_desc)
|
||||
|
||||
if elapsed_str:
|
||||
action_parts.append(elapsed_str)
|
||||
|
||||
if score_str:
|
||||
action_parts.append(score_str)
|
||||
|
||||
action_log_line = " ".join(action_parts)
|
||||
|
||||
# 写入 actions.log 文件
|
||||
try:
|
||||
import path_config
|
||||
actions_log_path = path_config.get_actions_log_path()
|
||||
log_dir = path_config.get_logs_dir()
|
||||
except Exception:
|
||||
actions_log_path = os.path.join(
|
||||
os.path.dirname(__file__), "logs", "actions.log"
|
||||
)
|
||||
log_dir = os.path.dirname(actions_log_path)
|
||||
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# 检测标签变化
|
||||
if not hasattr(analyser, "_last_action_tag"):
|
||||
analyser._last_action_tag = None
|
||||
|
||||
current_tag = tag or "[日志]"
|
||||
try:
|
||||
import logging
|
||||
action_logger = logging.getLogger("action_logger")
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
action_logger.info("=" * 80)
|
||||
action_logger.info(action_log_line)
|
||||
analyser._last_action_tag = current_tag
|
||||
except Exception:
|
||||
if log_dir:
|
||||
with open(
|
||||
actions_log_path,
|
||||
"a",
|
||||
encoding="utf-8-sig",
|
||||
errors="replace",
|
||||
) as f:
|
||||
if (
|
||||
analyser._last_action_tag is not None
|
||||
and analyser._last_action_tag != current_tag
|
||||
):
|
||||
f.write("=" * 80 + "\n")
|
||||
analyser._last_action_tag = current_tag
|
||||
f.write(action_log_line + "\n")
|
||||
f.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 详细模式:保留标准logging输出(用于debug)
|
||||
try:
|
||||
import logging
|
||||
root_logger = logging.getLogger()
|
||||
if not root_logger.handlers:
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not hasattr(analyser, "_std_logger") or analyser._std_logger is None:
|
||||
try:
|
||||
from unified_logger import get_unified_logger
|
||||
analyser._std_logger = get_unified_logger("douyin.fudai")
|
||||
except ImportError:
|
||||
try:
|
||||
from douyin.logging import douyin_logger
|
||||
analyser._std_logger = douyin_logger.get_logger("douyin")
|
||||
except Exception:
|
||||
analyser._std_logger = logging.getLogger("douyin.fudai")
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
if root_logger.handlers:
|
||||
std_msg_parts = [f"[{tag}]"]
|
||||
if caller_info:
|
||||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||||
if msg:
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||||
std_msg_parts.append(masked_msg)
|
||||
except ImportError:
|
||||
std_msg_parts.append(str(msg))
|
||||
|
||||
masked_fields: Dict[str, Any] = {}
|
||||
try:
|
||||
from unified_logger import SensitiveDataMasker
|
||||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||||
except ImportError:
|
||||
masked_fields = fields
|
||||
|
||||
for k, v in masked_fields.items():
|
||||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||||
continue
|
||||
if v is not None:
|
||||
std_msg_parts.append(f"{k}={v}")
|
||||
|
||||
log_message = " ".join(std_msg_parts)
|
||||
|
||||
exc_info = fields.get("exc_info")
|
||||
if exc_info is None:
|
||||
if sys.exc_info()[0] is not None:
|
||||
exc_info = sys.exc_info()
|
||||
|
||||
level = getattr(logging, log_level, logging.INFO)
|
||||
extra_data = {
|
||||
"caller": caller_info,
|
||||
"suppress_console_output": True,
|
||||
"suppress_file_output": True,
|
||||
}
|
||||
if exc_info:
|
||||
root_logger.log(level, log_message, exc_info=exc_info, extra=extra_data)
|
||||
else:
|
||||
root_logger.log(level, log_message, extra=extra_data)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -18,7 +18,7 @@ def wait_for_lottery_result(
|
||||
lastsecond: int,
|
||||
future_timestamp: float,
|
||||
reservation_after_action_pending: bool,
|
||||
reservation_should_preempt_callback,
|
||||
reservation_should_preempt_callback=None,
|
||||
) -> Tuple[bool, int, float | None, int | None]:
|
||||
"""兼容实现:按原始签名等待开奖,当前版本只做时间等待与简单抢占判断。"""
|
||||
start = time.time()
|
||||
@@ -36,15 +36,7 @@ def wait_for_lottery_result(
|
||||
detect_attempts += 1
|
||||
if first_detect_ts is None:
|
||||
first_detect_ts = time.time()
|
||||
# 若有"预约应抢占"回调,则在等待期间尊重其判断
|
||||
try:
|
||||
if (
|
||||
reservation_should_preempt_callback is not None
|
||||
and reservation_should_preempt_callback()
|
||||
):
|
||||
return True, detect_attempts, first_detect_ts, initial_check_result or 0
|
||||
except Exception:
|
||||
pass
|
||||
# 抢占逻辑已删除,直接继续等待
|
||||
try:
|
||||
analyser.operation.delay(step_s)
|
||||
except Exception:
|
||||
|
||||
@@ -189,6 +189,7 @@ def add_reservation_core_logic(
|
||||
bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。
|
||||
"""
|
||||
start_time = time.time()
|
||||
step_start_time = start_time
|
||||
|
||||
ft = float(item.get("future_ts") or 0.0)
|
||||
content = str(item.get("content") or "")
|
||||
@@ -196,6 +197,18 @@ def add_reservation_core_logic(
|
||||
room_title = str(item.get("room_title") or "")
|
||||
room_title_normalized = _normalize_room_title_for_matching(room_title)
|
||||
|
||||
# 步骤1: 参数处理和规范化
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤1: 参数处理和规范化",
|
||||
log_type="OP",
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
step_start_time = time.time()
|
||||
|
||||
# 添加函数入口日志
|
||||
try:
|
||||
from datetime import datetime
|
||||
@@ -234,6 +247,18 @@ def add_reservation_core_logic(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 步骤2: 查找是否已存在相同预约
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤2: 开始查找是否已存在相同预约",
|
||||
log_type="OP",
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
step_start_time = time.time()
|
||||
|
||||
same_idx: Optional[int] = None
|
||||
for idx, r in enumerate(reservations):
|
||||
try:
|
||||
@@ -357,6 +382,19 @@ def add_reservation_core_logic(
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 步骤3: 相似度匹配完成
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤3: 相似度匹配完成",
|
||||
log_type="OP",
|
||||
same_idx=same_idx,
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
step_start_time = time.time()
|
||||
|
||||
if same_idx is not None:
|
||||
# 若新记录价值更高,则更新
|
||||
try:
|
||||
@@ -401,9 +439,35 @@ def add_reservation_core_logic(
|
||||
pass
|
||||
reservations.append(dict(item))
|
||||
|
||||
# 步骤4: 添加/更新预约完成
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤4: 添加/更新预约完成",
|
||||
log_type="OP",
|
||||
same_idx=same_idx,
|
||||
queue_len_after=len(reservations),
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
step_start_time = time.time()
|
||||
|
||||
# 排序 + 按上限裁剪
|
||||
_sort_reservations_inplace(reservations)
|
||||
|
||||
# 步骤5: 排序完成
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤5: 排序完成",
|
||||
log_type="OP",
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
step_start_time = time.time()
|
||||
|
||||
queue_full = False
|
||||
if (
|
||||
max_reservations is not None
|
||||
@@ -485,6 +549,19 @@ def add_reservation_core_logic(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 步骤6: 队列裁剪和状态写入完成
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 步骤6: 队列裁剪和状态写入完成",
|
||||
log_type="OP",
|
||||
queue_full=queue_full,
|
||||
queue_len_final=len(reservations),
|
||||
elapsed_seconds=round(time.time() - step_start_time, 3),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 添加函数完成日志
|
||||
try:
|
||||
elapsed = time.time() - start_time
|
||||
@@ -691,12 +768,7 @@ def handle_queue_full_wait_at_earliest(
|
||||
)
|
||||
|
||||
# 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数)
|
||||
poll_before: float = 10.0
|
||||
try:
|
||||
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
|
||||
except Exception:
|
||||
pass
|
||||
poll_before = max(0.0, poll_before)
|
||||
poll_before: float = 0.0
|
||||
|
||||
# 如果已经在锁定期内,不需要重复回退
|
||||
if focus_until > 0 and now_ts < focus_until:
|
||||
@@ -986,7 +1058,7 @@ def process_reservation_attend_window(
|
||||
|
||||
# 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数)
|
||||
try:
|
||||
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
|
||||
poll_before = 0.0
|
||||
except Exception:
|
||||
poll_before = 10.0
|
||||
poll_before = max(0.0, poll_before)
|
||||
|
||||
@@ -874,10 +874,6 @@ class StageHandler:
|
||||
)
|
||||
or 120
|
||||
)
|
||||
poll_before = float(
|
||||
getattr(analyser, "poll_before_open_seconds", 10.0)
|
||||
or 10.0
|
||||
)
|
||||
time_window_start_ts = ft - join_ahead
|
||||
if now_ts < time_window_start_ts:
|
||||
try:
|
||||
|
||||
@@ -226,16 +226,6 @@ class ConfigManager:
|
||||
config["reservation_back_total_timeout_seconds"] or 20.0
|
||||
)
|
||||
|
||||
if "reservation_preempt_min_value_yuan" in config:
|
||||
analyser.reservation_preempt_min_value_yuan = float(
|
||||
config["reservation_preempt_min_value_yuan"] or 0.0
|
||||
)
|
||||
|
||||
if "poll_before_open_seconds" in config:
|
||||
analyser.poll_before_open_seconds = int(
|
||||
config["poll_before_open_seconds"] or 10
|
||||
)
|
||||
|
||||
if "reset_after_swipes_enabled" in config:
|
||||
analyser.reset_after_swipes_enabled = bool(
|
||||
config["reset_after_swipes_enabled"]
|
||||
|
||||
+206
-129
@@ -305,6 +305,47 @@ def main():
|
||||
elif not devs:
|
||||
on_line("[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)")
|
||||
|
||||
def save_logging_config():
|
||||
"""保存日志配置到配置文件"""
|
||||
try:
|
||||
# 读取当前配置
|
||||
cfg = read_config()
|
||||
|
||||
# 更新日志相关配置
|
||||
if 'logging' not in cfg:
|
||||
cfg['logging'] = {}
|
||||
|
||||
cfg['logging']['log_format_mode'] = logging_format_mode_var.get()
|
||||
cfg['logging']['beautify_output'] = bool(logging_beautify_var.get())
|
||||
cfg['logging']['color_output'] = bool(logging_color_var.get())
|
||||
cfg['logging']['show_timestamps'] = bool(logging_show_timestamps_var.get())
|
||||
cfg['logging']['debug_detail_level'] = logging_debug_level_var.get()
|
||||
cfg['logging']['error_detail_level'] = logging_error_level_var.get()
|
||||
cfg['logging']['action_log_format'] = logging_action_format_var.get()
|
||||
cfg['logging']['enable_monitor'] = bool(logging_enable_monitor_var.get())
|
||||
cfg['logging']['keep_days'] = int(logging_keep_days_var.get())
|
||||
cfg['logging']['compress_logs'] = bool(logging_compress_logs_var.get())
|
||||
cfg['logging']['max_total_size_gb'] = float(logging_max_total_size_gb_var.get())
|
||||
cfg['logging']['compress_after_days'] = int(logging_compress_after_days_var.get())
|
||||
cfg['logging']['monitor_warning_mb'] = float(logging_monitor_warning_mb_var.get())
|
||||
cfg['logging']['monitor_critical_mb'] = float(logging_monitor_critical_mb_var.get())
|
||||
cfg['logging']['performance_tracking'] = {
|
||||
'enabled': bool(logging_performance_enabled_var.get()),
|
||||
'track_function_calls': bool(logging_track_functions_var.get())
|
||||
}
|
||||
|
||||
# 更新GUI主题
|
||||
if 'gui' not in cfg:
|
||||
cfg['gui'] = {}
|
||||
cfg['gui']['theme'] = gui_theme_var.get()
|
||||
|
||||
# 保存配置
|
||||
write_config(cfg)
|
||||
|
||||
on_line("[配置] 日志配置已保存")
|
||||
except Exception as e:
|
||||
on_line(f"[配置] 保存日志配置失败:{e}")
|
||||
|
||||
refresh_devices_btn = ttk.Button(top, text="刷新设备", command=refresh_devices)
|
||||
refresh_devices_btn.pack(side=LEFT, padx=(0, 20))
|
||||
|
||||
@@ -403,9 +444,6 @@ def main():
|
||||
reservation_back_swipe_delay_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
reservation_preempt_min_value_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_preempt_min_value", 0) or 0)
|
||||
)
|
||||
fudai_find_max_attempts_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
|
||||
)
|
||||
@@ -663,6 +701,9 @@ def main():
|
||||
logging_action_format_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
|
||||
)
|
||||
logging_format_mode_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("log_format_mode", "simple"))
|
||||
)
|
||||
logging_monitor_warning_mb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("monitor_warning_mb", 500.0) or 500.0)
|
||||
)
|
||||
@@ -932,7 +973,7 @@ def main():
|
||||
res_r5, text="预约回退校验", variable=reservation_back_verify_enabled_var
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 回退滑延迟和预约抢占最小价值
|
||||
# 回退滑延迟
|
||||
res_r6 = ttk.Frame(reservation_box)
|
||||
res_r6.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(res_r6, text="回退滑延迟(秒):").pack(side=LEFT)
|
||||
@@ -944,16 +985,6 @@ def main():
|
||||
textvariable=reservation_back_swipe_delay_var,
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r6, text="预约抢占最小价值(元):").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
res_r6,
|
||||
from_=0,
|
||||
to=99999,
|
||||
increment=0.01,
|
||||
format="%.2f",
|
||||
textvariable=reservation_preempt_min_value_var,
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 标签页4:养号设置
|
||||
yanghao_tab = ttk.Frame(left_notebook)
|
||||
@@ -1470,136 +1501,123 @@ def main():
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志配置
|
||||
logging_config_box = ttk.LabelFrame(debug_container, text="日志配置")
|
||||
logging_config_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
# 标签页5:日志配置
|
||||
logging_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.add(logging_tab, text="日志配置")
|
||||
|
||||
# 日志配置容器
|
||||
logging_container = ttk.Frame(logging_tab)
|
||||
logging_container.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||||
|
||||
# 日志格式设置
|
||||
log_format_box = ttk.LabelFrame(logging_container, text="日志格式")
|
||||
log_format_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
# 日志格式模式
|
||||
log_format_r1 = ttk.Frame(log_format_box)
|
||||
log_format_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_format_r1, text="日志格式模式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_format_r1,
|
||||
values=["simple", "detailed"],
|
||||
textvariable=logging_format_mode_var,
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_format_r1, text="(simple=简洁模式,detailed=详细模式用于debug)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志美化选项
|
||||
log_r1 = ttk.Frame(logging_config_box)
|
||||
log_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
log_format_r2 = ttk.Frame(log_format_box)
|
||||
log_format_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(
|
||||
log_r1,
|
||||
log_format_r2,
|
||||
text="启用日志美化",
|
||||
variable=logging_beautify_var,
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_r1,
|
||||
log_format_r2,
|
||||
text="启用颜色显示",
|
||||
variable=logging_color_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 监控与清理开关
|
||||
log_r1b = ttk.Frame(logging_config_box)
|
||||
log_r1b.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
log_r1b,
|
||||
text="启用日志监控(超限告警/触发清理)",
|
||||
variable=logging_enable_monitor_var,
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_r1b,
|
||||
text="压缩旧日志",
|
||||
variable=logging_compress_logs_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 日志详细程度
|
||||
log_r2 = ttk.Frame(logging_config_box)
|
||||
log_r2.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Label(log_r2, text="调试日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_r2,
|
||||
values=["normal", "detailed", "minimal"],
|
||||
textvariable=logging_debug_level_var,
|
||||
state="readonly",
|
||||
width=10,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_r2, text="错误日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_r2,
|
||||
values=["full", "basic", "minimal"],
|
||||
textvariable=logging_error_level_var,
|
||||
state="readonly",
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 行为日志格式
|
||||
log_r3 = ttk.Frame(logging_config_box)
|
||||
log_r3.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Label(log_r3, text="行为日志格式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_r3,
|
||||
values=["concise", "detailed", "minimal"],
|
||||
textvariable=logging_action_format_var,
|
||||
state="readonly",
|
||||
width=10,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Checkbutton(
|
||||
log_r3,
|
||||
log_format_r2,
|
||||
text="显示时间戳",
|
||||
variable=logging_show_timestamps_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 界面主题选择
|
||||
log_theme_row = ttk.Frame(logging_config_box)
|
||||
log_theme_row.pack(fill=X, padx=10, pady=(6, 10))
|
||||
ttk.Label(log_theme_row, text="界面主题:").pack(side=LEFT)
|
||||
# 日志详细程度设置
|
||||
log_detail_box = ttk.LabelFrame(logging_container, text="日志详细程度")
|
||||
log_detail_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_detail_r1 = ttk.Frame(log_detail_box)
|
||||
log_detail_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_detail_r1, text="调试日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_theme_row,
|
||||
values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"],
|
||||
textvariable=gui_theme_var,
|
||||
log_detail_r1,
|
||||
values=["normal", "detailed", "minimal"],
|
||||
textvariable=logging_debug_level_var,
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
ttk.Label(log_theme_row, text="(更改后请保存并重启以完全应用主题)").pack(
|
||||
side=LEFT, padx=(12, 0)
|
||||
)
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_detail_r1, text="错误日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r1,
|
||||
values=["full", "basic", "minimal"],
|
||||
textvariable=logging_error_level_var,
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 性能追踪
|
||||
log_r4 = ttk.Frame(logging_config_box)
|
||||
log_r4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
perf_frame = ttk.LabelFrame(log_r4, text="性能追踪")
|
||||
perf_frame.pack(fill=X, pady=(0, 0))
|
||||
log_detail_r2 = ttk.Frame(log_detail_box)
|
||||
log_detail_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_detail_r2, text="行为日志格式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r2,
|
||||
values=["concise", "detailed", "minimal"],
|
||||
textvariable=logging_action_format_var,
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Checkbutton(
|
||||
perf_frame,
|
||||
text="启用性能追踪",
|
||||
variable=logging_performance_enabled_var,
|
||||
).pack(side=LEFT, padx=10, pady=5)
|
||||
ttk.Checkbutton(
|
||||
perf_frame,
|
||||
text="追踪函数调用",
|
||||
variable=logging_track_functions_var,
|
||||
).pack(side=LEFT, padx=(20, 0), pady=5)
|
||||
# 流式后台截图开关(GUI 控制)
|
||||
ttk.Checkbutton(
|
||||
perf_frame,
|
||||
text="启用流式后台截图(加速但可能导致并发读取)",
|
||||
variable=streaming_enabled_var,
|
||||
).pack(side=LEFT, padx=(20, 0), pady=5)
|
||||
log_detail_r2,
|
||||
text="启用日志监控(超限告警/触发清理)",
|
||||
variable=logging_enable_monitor_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 清理策略参数
|
||||
log_r4b = ttk.Frame(logging_config_box)
|
||||
log_r4b.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_r4b, text="保留天数:").pack(side=LEFT)
|
||||
# 日志管理设置
|
||||
log_manage_box = ttk.LabelFrame(logging_container, text="日志管理")
|
||||
log_manage_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_manage_r1 = ttk.Frame(log_manage_box)
|
||||
log_manage_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
log_manage_r1,
|
||||
text="压缩旧日志",
|
||||
variable=logging_compress_logs_var,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(log_manage_r1, text="保留天数:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
log_r4b,
|
||||
log_manage_r1,
|
||||
from_=1,
|
||||
to=365,
|
||||
increment=1,
|
||||
textvariable=logging_keep_days_var,
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_r4b, text="总量上限(GB):").pack(side=LEFT)
|
||||
ttk.Label(log_manage_r1, text="总量上限(GB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_r4b,
|
||||
log_manage_r1,
|
||||
from_=0.1,
|
||||
to=100.0,
|
||||
increment=0.1,
|
||||
textvariable=logging_max_total_size_gb_var,
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_r4b, text="压缩阈值(天):").pack(side=LEFT)
|
||||
ttk.Label(log_manage_r1, text="压缩阈值(天):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_r4b,
|
||||
log_manage_r1,
|
||||
from_=0,
|
||||
to=365,
|
||||
increment=1,
|
||||
@@ -1607,21 +1625,20 @@ def main():
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 日志监控阈值(也用于触发自动清理)
|
||||
log_r5 = ttk.Frame(logging_config_box)
|
||||
log_r5.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_r5, text="日志总大小警告阈值(MB):").pack(side=LEFT)
|
||||
log_manage_r2 = ttk.Frame(log_manage_box)
|
||||
log_manage_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_manage_r2, text="日志总大小警告阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_r5,
|
||||
log_manage_r2,
|
||||
from_=50,
|
||||
to=20000,
|
||||
increment=50,
|
||||
textvariable=logging_monitor_warning_mb_var,
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_r5, text="严重阈值(MB):").pack(side=LEFT)
|
||||
ttk.Label(log_manage_r2, text="严重阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_r5,
|
||||
log_manage_r2,
|
||||
from_=100,
|
||||
to=100000,
|
||||
increment=100,
|
||||
@@ -1629,7 +1646,59 @@ def main():
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 标签页6:关键词
|
||||
# 性能追踪设置
|
||||
perf_box = ttk.LabelFrame(logging_container, text="性能追踪")
|
||||
perf_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
perf_r1 = ttk.Frame(perf_box)
|
||||
perf_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="启用性能追踪",
|
||||
variable=logging_performance_enabled_var,
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="追踪函数调用",
|
||||
variable=logging_track_functions_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="流式后台截图(加速但可能导致并发读取)",
|
||||
variable=streaming_enabled_var,
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 界面主题选择
|
||||
theme_box = ttk.LabelFrame(logging_container, text="界面设置")
|
||||
theme_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
theme_r1 = ttk.Frame(theme_box)
|
||||
theme_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Label(theme_r1, text="界面主题:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
theme_r1,
|
||||
values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"],
|
||||
textvariable=gui_theme_var,
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
ttk.Label(theme_r1, text="(更改后请保存并重启以完全应用主题)").pack(
|
||||
side=LEFT, padx=(12, 0)
|
||||
)
|
||||
|
||||
# 保存配置按钮
|
||||
save_config_frame = ttk.Frame(logging_container)
|
||||
save_config_frame.pack(fill=X, pady=(10, 0))
|
||||
ttk.Button(
|
||||
save_config_frame,
|
||||
text="保存日志配置",
|
||||
command=save_logging_config,
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
# 标签页6:调试参数
|
||||
debug_tab = ttk.Frame(left_notebook)
|
||||
|
||||
# 标签页7:关键词
|
||||
keywords_tab = ttk.Frame(left_notebook)
|
||||
left_notebook.add(keywords_tab, text="关键词")
|
||||
|
||||
@@ -1708,9 +1777,6 @@ def main():
|
||||
reservation_back_swipe_delay_var.set(
|
||||
float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
reservation_preempt_min_value_var.set(
|
||||
float(cfg.get("reservation_preempt_min_value", 0) or 0)
|
||||
)
|
||||
fudai_find_max_attempts_var.set(int(cfg.get("fudai_find_max_attempts", 0) or 0))
|
||||
fudai_icon_retry_delay_seconds_var.set(
|
||||
float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
@@ -1845,6 +1911,9 @@ def main():
|
||||
logging_action_format_var.set(
|
||||
str(logging_config.get("action_log_format", "concise") or "concise")
|
||||
)
|
||||
logging_format_mode_var.set(
|
||||
str(logging_config.get("log_format_mode", "simple") or "simple")
|
||||
)
|
||||
perf_cfg = logging_config.get("performance_tracking", {})
|
||||
if isinstance(perf_cfg, dict):
|
||||
logging_performance_enabled_var.set(bool(perf_cfg.get("enabled", True)))
|
||||
@@ -1983,9 +2052,6 @@ def main():
|
||||
cfg2["reservation_back_swipe_delay"] = float(
|
||||
reservation_back_swipe_delay_var.get() or 0
|
||||
)
|
||||
cfg2["reservation_preempt_min_value"] = float(
|
||||
reservation_preempt_min_value_var.get() or 0
|
||||
)
|
||||
cfg2["fudai_find_max_attempts"] = int(fudai_find_max_attempts_var.get() or 0)
|
||||
cfg2["fudai_icon_retry_delay_seconds"] = float(
|
||||
fudai_icon_retry_delay_seconds_var.get() or 0.6
|
||||
@@ -2095,6 +2161,9 @@ def main():
|
||||
cfg2["logging"]["action_log_format"] = str(
|
||||
logging_action_format_var.get() or "concise"
|
||||
)
|
||||
cfg2["logging"]["log_format_mode"] = str(
|
||||
logging_format_mode_var.get() or "simple"
|
||||
)
|
||||
cfg2["logging"]["monitor_warning_mb"] = float(
|
||||
logging_monitor_warning_mb_var.get() or 500.0
|
||||
)
|
||||
@@ -2817,7 +2886,9 @@ def main():
|
||||
try:
|
||||
op_type = get_operation_type(line)
|
||||
if op_type:
|
||||
apply_operation_color(log_text, start_pos, end_pos, line, current_theme)
|
||||
apply_operation_color(
|
||||
log_text, start_pos, end_pos, line, current_theme
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
@@ -2836,7 +2907,10 @@ def main():
|
||||
|
||||
log_search_matches = [] # 存储所有匹配的位置
|
||||
log_current_match_index = -1 # 当前匹配的索引
|
||||
def _generic_search_widget(widget, search_var, matches_list, current_index, direction=1):
|
||||
|
||||
def _generic_search_widget(
|
||||
widget, search_var, matches_list, current_index, direction=1
|
||||
):
|
||||
"""通用的文本控件搜索函数:在 widget 中根据 search_var 搜索并高亮。
|
||||
|
||||
- widget: 文本控件(ScrolledText)
|
||||
@@ -2919,7 +2993,11 @@ def main():
|
||||
"""在运行日志中搜索文本(调用通用搜索实现)"""
|
||||
nonlocal log_search_matches, log_current_match_index
|
||||
log_current_match_index = _generic_search_widget(
|
||||
log_text, log_search_var, log_search_matches, log_current_match_index, direction
|
||||
log_text,
|
||||
log_search_var,
|
||||
log_search_matches,
|
||||
log_current_match_index,
|
||||
direction,
|
||||
)
|
||||
|
||||
def search_next_in_log():
|
||||
@@ -2950,7 +3028,9 @@ def main():
|
||||
ttk.Button(log_search_frame, text="刷新", command=refresh_run_log).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Separator(log_search_frame, orient="vertical").pack(side=LEFT, fill=Y, padx=5, pady=3)
|
||||
ttk.Separator(log_search_frame, orient="vertical").pack(
|
||||
side=LEFT, fill=Y, padx=5, pady=3
|
||||
)
|
||||
ttk.Label(log_search_frame, text="搜索:").pack(side=LEFT)
|
||||
# 把搜索输入框放在分隔符后
|
||||
log_search_entry.pack(side=LEFT, padx=(0, 5))
|
||||
@@ -3244,9 +3324,6 @@ def main():
|
||||
reservation_back_swipe_delay=float(
|
||||
reservation_back_swipe_delay_var.get() or 1.0
|
||||
),
|
||||
reservation_preempt_min_value=float(
|
||||
reservation_preempt_min_value_var.get() or 1000
|
||||
),
|
||||
fudai_find_max_attempts=int(fudai_find_max_attempts_var.get() or 5),
|
||||
enable_ocr_mode1=bool(enable_ocr_mode1_var.get()),
|
||||
fudai_template_match_enabled=bool(fudai_template_match_enabled_var.get()),
|
||||
|
||||
+35
-25
@@ -106,7 +106,6 @@ class RunParams:
|
||||
high_value_room_revisit_only_current_run: bool
|
||||
reservation_back_verify_enabled: bool
|
||||
reservation_back_swipe_delay: float
|
||||
reservation_preempt_min_value: float
|
||||
fudai_find_max_attempts: int
|
||||
enable_ocr_mode1: bool
|
||||
fudai_template_match_enabled: bool
|
||||
@@ -123,6 +122,8 @@ class Runner:
|
||||
self._on_line = on_line
|
||||
self._reader_thread: Optional[threading.Thread] = None
|
||||
self._lock = threading.Lock()
|
||||
self._log: list[str] = []
|
||||
self._log_capacity: int = 4000
|
||||
|
||||
# 统计相关
|
||||
self._start_ts: Optional[float] = None
|
||||
@@ -157,6 +158,19 @@ class Runner:
|
||||
def is_running(self) -> bool:
|
||||
return self._proc is not None and self._proc.poll() is None
|
||||
|
||||
def _append_log_line(self, line: str) -> None:
|
||||
if line is None:
|
||||
return
|
||||
with self._lock:
|
||||
self._log.append(line)
|
||||
cap = self._log_capacity
|
||||
if cap > 0 and len(self._log) > cap:
|
||||
del self._log[: len(self._log) - cap]
|
||||
|
||||
def _emit_line(self, line: str) -> None:
|
||||
self._append_log_line(line)
|
||||
self._on_line(line)
|
||||
|
||||
def _inc(self, key: str, n: int = 1) -> None:
|
||||
with self._lock:
|
||||
self._counters[key] = int(self._counters.get(key, 0)) + int(n)
|
||||
@@ -962,13 +976,6 @@ class Runner:
|
||||
str(params.reservation_back_swipe_delay),
|
||||
]
|
||||
|
||||
# 预约抢占最小价值
|
||||
if params.reservation_preempt_min_value > 0:
|
||||
cmd += [
|
||||
"--reservation-preempt-min-value",
|
||||
str(params.reservation_preempt_min_value),
|
||||
]
|
||||
|
||||
# 找福袋最大尝试次数
|
||||
if params.fudai_find_max_attempts > 0:
|
||||
cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)]
|
||||
@@ -1023,7 +1030,7 @@ class Runner:
|
||||
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
|
||||
env["ADB_EXECUTABLE"] = adb_exe
|
||||
else:
|
||||
self._on_line(
|
||||
self._emit_line(
|
||||
"[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH"
|
||||
)
|
||||
|
||||
@@ -1069,6 +1076,7 @@ class Runner:
|
||||
}
|
||||
self._events = []
|
||||
self._wins = []
|
||||
self._log = []
|
||||
|
||||
def _reader():
|
||||
assert self._proc is not None
|
||||
@@ -1081,7 +1089,7 @@ class Runner:
|
||||
for line in out:
|
||||
has_output = True
|
||||
cleaned_line = line.rstrip("\n")
|
||||
self._on_line(cleaned_line)
|
||||
self._emit_line(cleaned_line)
|
||||
try:
|
||||
self._update_stats_from_line(cleaned_line)
|
||||
except Exception:
|
||||
@@ -1094,21 +1102,23 @@ class Runner:
|
||||
|
||||
# 如果进程立即退出且没有输出,说明可能有问题
|
||||
if not has_output and rc != 0:
|
||||
self._on_line(f"[警告] 进程立即退出,退出码={rc},没有输出")
|
||||
self._on_line(
|
||||
self._emit_line(
|
||||
f"[警告] 进程立即退出,退出码={rc},没有输出"
|
||||
)
|
||||
self._emit_line(
|
||||
"[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误"
|
||||
)
|
||||
else:
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
self._emit_line(f"[进程结束] exit_code={rc}")
|
||||
except Exception as e:
|
||||
# 读取输出时出错
|
||||
try:
|
||||
self._on_line(f"[错误] 读取进程输出失败: {e}")
|
||||
self._emit_line(f"[错误] 读取进程输出失败: {e}")
|
||||
rc = self._proc.poll()
|
||||
if rc is not None:
|
||||
with self._lock:
|
||||
self._exit_code = rc
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
self._emit_line(f"[进程结束] exit_code={rc}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1131,14 +1141,14 @@ class Runner:
|
||||
try:
|
||||
adb_exe = find_adb_executable()
|
||||
if not adb_exe:
|
||||
self._on_line("[错误] 未找到 adb.exe")
|
||||
self._emit_line("[错误] 未找到 adb.exe")
|
||||
return False
|
||||
|
||||
# 如果没有指定设备ID,尝试获取第一个可用设备
|
||||
if not device_id or device_id.strip() == "":
|
||||
devices = list_adb_devices(adb_exe)
|
||||
if not devices:
|
||||
self._on_line("[错误] 未找到可用设备")
|
||||
self._emit_line("[错误] 未找到可用设备")
|
||||
return False
|
||||
device_id = devices[0]
|
||||
|
||||
@@ -1155,29 +1165,29 @@ class Runner:
|
||||
)
|
||||
|
||||
if proc.returncode == 0:
|
||||
self._on_line(f"[手动操作] 已发送返回键到设备: {device_id}")
|
||||
self._emit_line(f"[手动操作] 已发送返回键到设备: {device_id}")
|
||||
return True
|
||||
else:
|
||||
error_msg = proc.stderr or proc.stdout or "未知错误"
|
||||
self._on_line(f"[错误] 发送返回键失败: {error_msg}")
|
||||
self._emit_line(f"[错误] 发送返回键失败: {error_msg}")
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
self._on_line("[错误] 发送返回键超时")
|
||||
self._emit_line("[错误] 发送返回键超时")
|
||||
return False
|
||||
except Exception as e:
|
||||
self._on_line(f"[错误] 发送返回键异常: {str(e)}")
|
||||
self._emit_line(f"[错误] 发送返回键异常: {str(e)}")
|
||||
return False
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self.is_running():
|
||||
return
|
||||
assert self._proc is not None
|
||||
self._on_line("[停止] 正在终止进程...")
|
||||
self._emit_line("[停止] 正在终止进程...")
|
||||
self._proc.terminate()
|
||||
try:
|
||||
self._proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._on_line("[停止] 进程未退出,强制结束...")
|
||||
self._emit_line("[停止] 进程未退出,强制结束...")
|
||||
self._proc.kill()
|
||||
|
||||
def force_stop(self) -> None:
|
||||
@@ -1186,10 +1196,10 @@ class Runner:
|
||||
pid = self._pid
|
||||
proc = self._proc
|
||||
if not pid and not proc:
|
||||
self._on_line("[停止] 当前无记录中的运行进程")
|
||||
self._emit_line("[停止] 当前无记录中的运行进程")
|
||||
return
|
||||
|
||||
self._on_line(f"[停止] 强制终止进程 (pid={pid}) ...")
|
||||
self._emit_line(f"[停止] 强制终止进程 (pid={pid}) ...")
|
||||
|
||||
# 先尝试通过 Popen 对象 kill
|
||||
try:
|
||||
|
||||
@@ -1336,13 +1336,6 @@ class ProcRunner:
|
||||
rbd = 0.0
|
||||
if rbd > 0:
|
||||
cmd += ["--reservation-back-swipe-delay", str(rbd)]
|
||||
# 预约抢占最小价值(GUI 启动时可覆盖)
|
||||
try:
|
||||
rpmin = float(_pick("reservation_preempt_min_value", 0) or 0)
|
||||
except Exception:
|
||||
rpmin = 0.0
|
||||
if rpmin > 0:
|
||||
cmd += ["--reservation-preempt-min-value", str(rpmin)]
|
||||
# 找福袋最大尝试次数(GUI 启动时可覆盖)
|
||||
try:
|
||||
fudai_find_max_attempts = int(_pick("fudai_find_max_attempts", 0) or 0)
|
||||
@@ -1801,7 +1794,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
"fudai_icon_retry_delay_seconds",
|
||||
"fudai_icon_max_wait_seconds",
|
||||
"reservation_back_swipe_delay",
|
||||
"reservation_preempt_min_value",
|
||||
"high_value_fudai_threshold_yuan",
|
||||
}
|
||||
bool_keys = {
|
||||
|
||||
-18
@@ -238,12 +238,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
default=None,
|
||||
help="运行时覆盖:回退后滑动等待(秒),仅在未启用回退校验时生效,可加快回退速度",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reservation-preempt-min-value",
|
||||
type=float,
|
||||
default=None,
|
||||
help="运行时覆盖:预约抢占最小价值(元),低于该值的预约不会抢占当前任务",
|
||||
)
|
||||
p.add_argument(
|
||||
"--fudai-find-max-attempts",
|
||||
type=int,
|
||||
@@ -351,11 +345,6 @@ def main(argv: list[str]) -> int:
|
||||
analyser.resolution_ratio_x, analyser.resolution_ratio_y = (
|
||||
analyser.operation.get_device_resolution(device_id)
|
||||
)
|
||||
print(
|
||||
"[TEST-COMMENT] device_id={} res={}x{}".format(
|
||||
device_id, analyser.resolution_ratio_x, analyser.resolution_ratio_y
|
||||
)
|
||||
)
|
||||
|
||||
msg = str(getattr(args, "test_comment_text", "测试评论123") or "测试评论123")
|
||||
# 逐步截图
|
||||
@@ -541,13 +530,6 @@ def main(argv: list[str]) -> int:
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if getattr(args, "reservation_preempt_min_value", None) is not None:
|
||||
try:
|
||||
analyser.reservation_preempt_min_value_yuan = max(
|
||||
0.0, float(args.reservation_preempt_min_value)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 运行时覆盖:找福袋最大尝试次数
|
||||
if getattr(args, "fudai_find_max_attempts", None) is not None:
|
||||
try:
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
"""\
|
||||
模拟检查:预约回退 preempted=True 是否仍会导致 run_once_basic 提前 return。
|
||||
|
||||
背景:之前在 `process_reservation_attend_window` 返回 preempted=True 后,
|
||||
`run_once_basic()` 直接 return,导致锁定期内每轮都重复“预约回退成功”,
|
||||
但不会进入后续直播间识别/参与逻辑,观感为卡死。
|
||||
|
||||
本脚本做两件事:
|
||||
1) 用 AST 精确定位到包含“预约回退成功:进入回退处理”日志的 if preempted 分支
|
||||
2) 断言该分支 body 中不包含 `return` 语句(否则就是老 bug 复现)
|
||||
|
||||
运行:
|
||||
.venv/Scripts/python.exe tools/simulate_reservation_preempted_flow.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
TARGET_FILE = REPO_ROOT / "douyin" / "core" / "douyin_fudai.py"
|
||||
TARGET_LOG_SNIPPET = "[预约] 预约回退成功:进入回退处理(直接参与标志已移除)"
|
||||
|
||||
|
||||
class _FoundBlock(Exception):
|
||||
def __init__(self, has_return: bool, lineno: int) -> None:
|
||||
super().__init__("found")
|
||||
self.has_return = has_return
|
||||
self.lineno = lineno
|
||||
|
||||
|
||||
def _node_contains_return(node: ast.AST) -> bool:
|
||||
"""检查 node 子树中是否存在 return(忽略嵌套函数/类/lambda 内部的 return)。
|
||||
|
||||
目的:我们只关心 if preempted 分支本身是否直接 return,
|
||||
不应把分支里定义的 helper(例如 _write_state 的节流 return)算进去。
|
||||
"""
|
||||
|
||||
class _ReturnFinder(ast.NodeVisitor):
|
||||
def __init__(self) -> None:
|
||||
self.found = False
|
||||
|
||||
def visit_Return(self, _n: ast.Return) -> None: # noqa: N802
|
||||
self.found = True
|
||||
|
||||
def visit_FunctionDef(self, _n: ast.FunctionDef) -> None: # noqa: N802
|
||||
# 不进入嵌套函数
|
||||
return
|
||||
|
||||
def visit_AsyncFunctionDef(
|
||||
self, _n: ast.AsyncFunctionDef
|
||||
) -> None: # noqa: N802
|
||||
return
|
||||
|
||||
def visit_Lambda(self, _n: ast.Lambda) -> None: # noqa: N802
|
||||
return
|
||||
|
||||
def visit_ClassDef(self, _n: ast.ClassDef) -> None: # noqa: N802
|
||||
return
|
||||
|
||||
finder = _ReturnFinder()
|
||||
finder.visit(node)
|
||||
return finder.found
|
||||
|
||||
|
||||
def _node_contains_target_log(node: ast.AST) -> bool:
|
||||
"""粗略匹配:在该 node 子树中出现目标日志字符串常量。"""
|
||||
for sub in ast.walk(node):
|
||||
if isinstance(sub, ast.Constant) and isinstance(sub.value, str):
|
||||
if TARGET_LOG_SNIPPET in sub.value:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _check() -> tuple[bool, int]:
|
||||
src = TARGET_FILE.read_text(encoding="utf-8")
|
||||
tree = ast.parse(src, filename=str(TARGET_FILE))
|
||||
|
||||
parent: dict[ast.AST, ast.AST] = {}
|
||||
|
||||
class _ParentBuilder(ast.NodeVisitor):
|
||||
def generic_visit(self, node: ast.AST) -> None:
|
||||
for child in ast.iter_child_nodes(node):
|
||||
parent[child] = node
|
||||
super().generic_visit(node)
|
||||
|
||||
_ParentBuilder().visit(tree)
|
||||
|
||||
def _is_self_log_kv_call(n: ast.AST) -> bool:
|
||||
if not isinstance(n, ast.Call):
|
||||
return False
|
||||
f = n.func
|
||||
return (
|
||||
isinstance(f, ast.Attribute)
|
||||
and f.attr == "_log_kv"
|
||||
and isinstance(f.value, ast.Name)
|
||||
and f.value.id == "self"
|
||||
)
|
||||
|
||||
def _call_has_target_string(n: ast.Call) -> bool:
|
||||
for arg in list(n.args) + [kw.value for kw in n.keywords]:
|
||||
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
|
||||
if TARGET_LOG_SNIPPET in arg.value:
|
||||
return True
|
||||
return False
|
||||
|
||||
# 定位 class fudai_analyse -> def run_once_basic
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.ClassDef) and node.name == "fudai_analyse":
|
||||
for item in node.body:
|
||||
if isinstance(item, ast.FunctionDef) and item.name == "run_once_basic":
|
||||
# 先找到目标日志对应的 _log_kv 调用点
|
||||
target_call: ast.Call | None = None
|
||||
for sub in ast.walk(item):
|
||||
if _is_self_log_kv_call(sub) and _call_has_target_string(sub):
|
||||
target_call = sub
|
||||
break
|
||||
|
||||
if target_call is None:
|
||||
continue
|
||||
|
||||
# 从调用点向上找最近的 enclosing If
|
||||
cur: ast.AST = target_call
|
||||
enclosing_if: ast.If | None = None
|
||||
while cur in parent:
|
||||
cur = parent[cur]
|
||||
if isinstance(cur, ast.If):
|
||||
enclosing_if = cur
|
||||
break
|
||||
|
||||
if enclosing_if is None:
|
||||
raise RuntimeError(
|
||||
"Found target log call but could not find enclosing If"
|
||||
)
|
||||
|
||||
has_return = _node_contains_return(enclosing_if)
|
||||
lineno = getattr(enclosing_if, "lineno", -1)
|
||||
raise _FoundBlock(has_return=has_return, lineno=lineno)
|
||||
|
||||
raise RuntimeError(f"未找到目标分支:{TARGET_LOG_SNIPPET}(文件:{TARGET_FILE})")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
try:
|
||||
_check()
|
||||
# 如果没抛 _FoundBlock,就说明没找到
|
||||
print("FAIL: could not locate target if(preempted) block")
|
||||
raise SystemExit(2)
|
||||
except _FoundBlock as e:
|
||||
if e.has_return:
|
||||
print(
|
||||
"FAIL: early return still exists (can cause reservation back spin) "
|
||||
f"at {TARGET_FILE}:{e.lineno}"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
print(
|
||||
"PASS: no early return in preempted=True branch; "
|
||||
"run_once_basic will continue with follow-up flow "
|
||||
f"(checked at {TARGET_FILE}:{e.lineno})"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,138 +0,0 @@
|
||||
"""\
|
||||
动态模拟:验证预约回退 preempted=True 后,run_once_basic 不会提前退出。
|
||||
|
||||
不连真机/不跑 ADB:
|
||||
- monkeypatch `douyin.reservation.douyin_reservation_logic.process_reservation_attend_window`
|
||||
令其返回 True(模拟已触发回退/抢占)。
|
||||
- 给 analyser 注入一个 FakeOperation,在后续流程的截图阶段抛出哨兵异常。
|
||||
|
||||
判定标准:
|
||||
- 若能捕获到“进入截图阶段”的哨兵异常 => 说明 preempted=True 后仍继续执行到后续流程(PASS)
|
||||
- 若 run_once_basic 正常 return 或在更早阶段异常退出 => FAIL
|
||||
|
||||
运行:
|
||||
.venv/Scripts/python.exe tools/simulate_reservation_preempted_flow_dynamic.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class _ReachedScreenshot(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class _FakeOperation:
|
||||
def get_screenshot(self, *_args, **_kwargs):
|
||||
raise _ReachedScreenshot("reached operation.get_screenshot")
|
||||
|
||||
def delay(self, _s: float) -> None:
|
||||
return
|
||||
|
||||
def get_top_package(self, _device_id: str) -> str:
|
||||
return "com.ss.android.ugc.aweme"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# 避免导入底层 OCR 时的初始化开销
|
||||
os.environ.setdefault("SKIP_OCR_INIT", "1")
|
||||
|
||||
# 确保能导入本仓库代码(避免因工作目录不同导致 ModuleNotFoundError)
|
||||
repo_root = Path(__file__).resolve().parents[1]
|
||||
if str(repo_root) not in sys.path:
|
||||
sys.path.insert(0, str(repo_root))
|
||||
|
||||
# 1) 导入 analyser
|
||||
from douyin.core.douyin_fudai import fudai_analyse # noqa: WPS433
|
||||
|
||||
# 2) monkeypatch reservation 回退逻辑:强制 preempted=True
|
||||
from douyin.reservation import douyin_reservation_logic # noqa: WPS433
|
||||
|
||||
original_fn = douyin_reservation_logic.process_reservation_attend_window
|
||||
|
||||
def _fake_process_reservation_attend_window(
|
||||
analyser,
|
||||
reservations,
|
||||
room_pos,
|
||||
reservation_focus_until_ts_ref,
|
||||
reservation_after_action_pending_ref,
|
||||
**_kwargs,
|
||||
) -> bool:
|
||||
# 模拟:已经回退成功并进入锁定期
|
||||
now = time.time()
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = now + 60.0
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = True
|
||||
return True
|
||||
|
||||
douyin_reservation_logic.process_reservation_attend_window = (
|
||||
_fake_process_reservation_attend_window
|
||||
)
|
||||
|
||||
try:
|
||||
# 3) 构造一个尽量“瘦”的 analyser(避免 __init__ 做太多事)
|
||||
analyser = fudai_analyse.__new__(fudai_analyse)
|
||||
|
||||
# 必要字段:日志、配置、状态
|
||||
analyser._log_kv = lambda *_a, **_k: None
|
||||
analyser.operation = _FakeOperation()
|
||||
analyser.device_id = "FAKE_DEVICE"
|
||||
|
||||
analyser._waiting_for_lottery_result = False
|
||||
analyser._lottery_result_expected_ts = 0.0
|
||||
|
||||
# 防止 30 分钟超时分支触发复杂自救
|
||||
analyser._last_successful_attend_ts = time.time()
|
||||
analyser._no_attend_timeout_minutes = 30.0
|
||||
analyser._run_start_ts = time.time()
|
||||
|
||||
# 预约相关
|
||||
analyser.high_value_fudai_enabled = True
|
||||
analyser.needswitch = True
|
||||
analyser.room_pos = 7
|
||||
analyser.reservation_back_swipe_delay = 0.6
|
||||
analyser.reservations = [
|
||||
{
|
||||
"future_ts": time.time() + 120.0,
|
||||
"prize_value_yuan": 999.0,
|
||||
"pos_seen": 4,
|
||||
"content": "",
|
||||
"room_title": "",
|
||||
"room_title_raw": "",
|
||||
}
|
||||
]
|
||||
analyser._first_run_once_basic = False
|
||||
|
||||
analyser._skip_stage_diagnosis_and_find_fudai = False
|
||||
|
||||
# 4) 执行:若 preempted=True 后继续,必然会到截图阶段并触发哨兵异常
|
||||
try:
|
||||
analyser.run_once_basic()
|
||||
except _ReachedScreenshot:
|
||||
print("PASS: preempted=True did not early-return; reached screenshot stage")
|
||||
return
|
||||
|
||||
print(
|
||||
"FAIL: run_once_basic returned before reaching screenshot stage "
|
||||
"(likely early-return or unexpected short-circuit)"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
except Exception as exc:
|
||||
print(f"FAIL: unexpected exception: {type(exc).__name__}: {exc}")
|
||||
traceback.print_exc()
|
||||
raise SystemExit(2)
|
||||
|
||||
finally:
|
||||
# 恢复 monkeypatch
|
||||
douyin_reservation_logic.process_reservation_attend_window = original_fn
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+37
-34
@@ -221,10 +221,10 @@ class UnifiedFormatter(logging.Formatter):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# 标准格式:时间戳(毫秒) - [级别] - [线程名] - [模块名:函数名:行号] - [traceId] - 消息
|
||||
# 简化的格式:时间戳 - [级别] - [模块] - 消息
|
||||
# 去掉了冗余的线程名、函数名、行号、traceId等信息,使日志更简洁
|
||||
self._detailed_format = (
|
||||
"%(asctime)s.%(msecs)03d - [%(levelname)s] - [%(threadName)s] - "
|
||||
"[%(name)s:%(funcName)s:%(lineno)d] - [traceId:%(traceId)s] - %(message)s"
|
||||
"%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s"
|
||||
)
|
||||
# 缓存:避免重复检查MDC
|
||||
self._last_mdc_check_time = 0.0
|
||||
@@ -235,43 +235,46 @@ class UnifiedFormatter(logging.Formatter):
|
||||
self._mdc_check_counter = 0 # 计数器,用于进一步优化
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
"""格式化日志记录,添加traceId(性能优化版本)"""
|
||||
# 获取traceId(快速路径,直接访问thread-local,无需调用get_all)
|
||||
trace_id = MDC.get_trace_id()
|
||||
if trace_id is None:
|
||||
trace_id = "N/A"
|
||||
"""格式化日志记录,简化显示以提高可读性"""
|
||||
# 只在DEBUG级别或错误时显示traceId
|
||||
if record.levelno <= logging.DEBUG or record.levelno >= logging.ERROR:
|
||||
trace_id = MDC.get_trace_id()
|
||||
if trace_id:
|
||||
record.traceId = trace_id # type: ignore[attr-defined]
|
||||
else:
|
||||
record.traceId = "N/A" # type: ignore[attr-defined]
|
||||
else:
|
||||
record.traceId = "" # type: ignore[attr-defined]
|
||||
|
||||
# 将traceId添加到record中
|
||||
record.traceId = trace_id # type: ignore[attr-defined]
|
||||
# 只在DEBUG级别显示完整的MDC信息
|
||||
if record.levelno <= logging.DEBUG:
|
||||
# 优化:使用计数器和时间戳双重检查,减少MDC查询频率
|
||||
self._mdc_check_counter += 1
|
||||
current_time = time.time()
|
||||
should_check_mdc = (
|
||||
current_time - self._last_mdc_check_time
|
||||
) > self._mdc_cache_ttl or self._mdc_check_counter >= 50 # 每50条记录强制检查一次
|
||||
|
||||
# 优化:使用计数器和时间戳双重检查,减少MDC查询频率
|
||||
self._mdc_check_counter += 1
|
||||
current_time = time.time()
|
||||
should_check_mdc = (
|
||||
current_time - self._last_mdc_check_time
|
||||
) > self._mdc_cache_ttl or self._mdc_check_counter >= 50 # 每50条记录强制检查一次
|
||||
if should_check_mdc:
|
||||
self._last_mdc_data = MDC.get_all()
|
||||
self._last_mdc_check_time = current_time
|
||||
self._mdc_check_counter = 0
|
||||
|
||||
if should_check_mdc:
|
||||
self._last_mdc_data = MDC.get_all()
|
||||
self._last_mdc_check_time = current_time
|
||||
self._mdc_check_counter = 0
|
||||
mdc_data = self._last_mdc_data
|
||||
if mdc_data:
|
||||
# 将MDC信息添加到消息中(排除traceId,避免重复)
|
||||
mdc_items = [(k, v) for k, v in mdc_data.items() if k != "traceId"]
|
||||
if mdc_items:
|
||||
# 优化:使用列表推导式,避免多次字符串拼接
|
||||
mdc_str = ", ".join(f"{k}={v}" for k, v in mdc_items)
|
||||
if mdc_str:
|
||||
record.msg = f"{record.msg} | MDC: {mdc_str}"
|
||||
|
||||
mdc_data = self._last_mdc_data
|
||||
if mdc_data:
|
||||
# 将MDC信息添加到消息中(排除traceId,避免重复)
|
||||
mdc_items = [(k, v) for k, v in mdc_data.items() if k != "traceId"]
|
||||
if mdc_items:
|
||||
# 优化:使用列表推导式,避免多次字符串拼接
|
||||
mdc_str = ", ".join(f"{k}={v}" for k, v in mdc_items)
|
||||
if mdc_str:
|
||||
record.msg = f"{record.msg} | MDC: {mdc_str}"
|
||||
|
||||
# 优化:只在消息较长或可能包含敏感信息时才进行脱敏
|
||||
# 进一步优化:缓存敏感关键词检查结果(对于相同消息)
|
||||
# 敏感信息脱敏(只对可能包含敏感信息的消息进行)
|
||||
if isinstance(record.msg, str):
|
||||
msg = record.msg
|
||||
# 快速检查:如果消息很短(<30字符),直接跳过脱敏(提高阈值以减少检查)
|
||||
if len(msg) > 30:
|
||||
# 快速检查:如果消息很短(<50字符),直接跳过脱敏
|
||||
if len(msg) > 50:
|
||||
# 使用更高效的检查:先检查长度,再检查关键词
|
||||
msg_lower = msg.lower()
|
||||
if any(
|
||||
|
||||
@@ -62,7 +62,6 @@ const DEFAULTS = {
|
||||
// 是否禁用福袋内容OCR识别(仅前端默认,实际值以 config.json 为准)
|
||||
fudai_disable_content_recognition: false,
|
||||
live_room_match_threshold: 0.8,
|
||||
reservation_preempt_min_value: 0,
|
||||
reservation_back_swipe_delay: 0.6,
|
||||
|
||||
// 定时禁抢福袋(默认 2-7 点)
|
||||
@@ -657,7 +656,6 @@ async function startRun() {
|
||||
reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled,
|
||||
reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay,
|
||||
fudai_find_max_attempts: cfgPart.fudai_find_max_attempts,
|
||||
reservation_preempt_min_value: cfgPart.reservation_preempt_min_value,
|
||||
});
|
||||
|
||||
// 检查返回结果
|
||||
|
||||
@@ -181,11 +181,6 @@
|
||||
<input id="live_room_match_threshold" class="input" data-key="live_room_match_threshold" data-type="float" type="number" min="0.0" max="1.0" step="0.01" />
|
||||
<div class="hint">模板匹配阈值(0.0~1.0),默认0.8,值越高越严格,建议≥0.8</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">预约抢占最小价�?�?</label>
|
||||
<input id="reservation_preempt_min_value" class="input" data-key="reservation_preempt_min_value" data-type="float" type="number" min="0" step="1" />
|
||||
<div class="hint">低于该价值的预约不会抢占当前任务�? 表示任何预约可抢�?/div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel" data-panel="filter" role="tabpanel" hidden>
|
||||
|
||||
Reference in new issue
Block a user