feat: 更新日志记录功能,添加自检脚本以检查 action_logger 初始化与绑定状态
This commit is contained in:
1 parent
57177ef7a2
commit
1105ed618f
7 files changed
+218
-38
No files matched your search
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""项目自检脚本:检查 action_logger 初始化与 analyser._log_kv 绑定。
|
||||
|
||||
用法: 在与项目相同的 Python 环境中运行:
|
||||
python check_action_logger.py
|
||||
"""
|
||||
import logging
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from douyin.logging import action_logger, douyin_logging_wrapper
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
import path_config
|
||||
|
||||
|
||||
def safe_repr(obj):
|
||||
try:
|
||||
return repr(obj)
|
||||
except Exception:
|
||||
return "<unreprable>"
|
||||
|
||||
|
||||
def main():
|
||||
print("=== action_logger / handler 状态 ===")
|
||||
try:
|
||||
al = logging.getLogger("action_logger")
|
||||
handlers = al.handlers
|
||||
print(
|
||||
"logger 'action_logger' handlers:",
|
||||
[(type(h).__name__, getattr(h, "baseFilename", None)) for h in handlers],
|
||||
)
|
||||
except Exception:
|
||||
print("获取 action_logger 失败:")
|
||||
traceback.print_exc()
|
||||
|
||||
print("\n=== action_logger 模块队列/监听器 ===")
|
||||
try:
|
||||
q = getattr(action_logger, "_log_queue", None)
|
||||
l = getattr(action_logger, "_queue_listener", None)
|
||||
print("_log_queue:", type(q).__name__ if q is not None else None)
|
||||
print("_queue_listener:", type(l).__name__ if l is not None else None)
|
||||
if l is not None:
|
||||
# QueueListener has method 'is_alive' if it's a Thread subclass; otherwise skip
|
||||
alive = getattr(l, "is_alive", lambda: False)()
|
||||
print("listener is_alive:", alive)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
print("\n=== actions.log 路径与权限 ===")
|
||||
try:
|
||||
path = path_config.get_actions_log_path()
|
||||
print("actions.log path:", path)
|
||||
try:
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(f"#check {time.time()}\n")
|
||||
print("已向 actions.log 追加一行(权限与磁盘检查通过)")
|
||||
except Exception as e:
|
||||
print("写入 actions.log 失败:", e)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
print("\n=== analyser._log_kv 绑定检查与试写 ===")
|
||||
try:
|
||||
a = fudai_analyse()
|
||||
print("analyser._log_kv repr:", safe_repr(a._log_kv))
|
||||
try:
|
||||
a._log_kv("check_point", "self_check", detail="test_write")
|
||||
print(
|
||||
"已调用 analyser._log_kv(...). 请查看 actions.log 是否包含该条目(或等待几秒队列刷新)"
|
||||
)
|
||||
except Exception as e:
|
||||
print("调用 analyser._log_kv 失败:", e)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
print("\n检查完成。")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"updated_ts": 1767412999.53979,
|
||||
"updated_ts": 1767414612.3390598,
|
||||
"reason": "startup_clear",
|
||||
"room_pos": 0,
|
||||
"current_room_title": "",
|
||||
|
||||
@@ -1805,7 +1805,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
analyser._log_kv(
|
||||
"福袋",
|
||||
f"识别福袋内容:{content_for_log[:100]}", # 在消息中直接包含内容,确保可见
|
||||
level="INFO",
|
||||
level="DEBUG",
|
||||
content=content_for_log, # 同时作为字段输出
|
||||
)
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ try:
|
||||
log_reservation_error,
|
||||
format_reservation_context,
|
||||
)
|
||||
|
||||
_RESERVATION_ERROR_UTILS_AVAILABLE = True
|
||||
except ImportError:
|
||||
# 如果导入失败,提供占位符函数
|
||||
@@ -146,7 +147,9 @@ class ReservationHandler:
|
||||
e,
|
||||
format_reservation_context(
|
||||
target_title=target_title[:50] if target_title else "",
|
||||
target_title_raw=target_title_raw[:50] if target_title_raw else "",
|
||||
target_title_raw=(
|
||||
target_title_raw[:50] if target_title_raw else ""
|
||||
),
|
||||
),
|
||||
level="WARNING",
|
||||
stage="根据标题查找位置",
|
||||
@@ -174,7 +177,9 @@ class ReservationHandler:
|
||||
"""
|
||||
# 检查配置项,只有在启用时才记录映射表
|
||||
try:
|
||||
mapping_enabled = bool(getattr(analyser, "record_room_title_mapping_enabled", True))
|
||||
mapping_enabled = bool(
|
||||
getattr(analyser, "record_room_title_mapping_enabled", True)
|
||||
)
|
||||
if not mapping_enabled:
|
||||
return
|
||||
except Exception:
|
||||
@@ -186,8 +191,10 @@ class ReservationHandler:
|
||||
# 读取当前直播间标题
|
||||
try:
|
||||
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
room_title, room_title_raw = douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
room_title, room_title_raw = (
|
||||
douyin_fudai_detail.read_live_room_title_core(
|
||||
analyser, y_pianyi_val
|
||||
)
|
||||
)
|
||||
|
||||
# 更新 analyser 的属性
|
||||
@@ -211,14 +218,20 @@ class ReservationHandler:
|
||||
log_type="OP",
|
||||
room_pos=room_pos,
|
||||
room_title=room_title[:50] if room_title else "",
|
||||
room_title_raw=(room_title_raw[:50] if room_title_raw else ""),
|
||||
map_size=len(getattr(analyser, "_room_pos_to_title_map", {})),
|
||||
room_title_raw=(
|
||||
room_title_raw[:50] if room_title_raw else ""
|
||||
),
|
||||
map_size=len(
|
||||
getattr(analyser, "_room_pos_to_title_map", {})
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
# 如果已存在,更新标题(可能标题有变化)
|
||||
old_title, old_title_raw = analyser._room_pos_to_title_map[room_pos]
|
||||
old_title, old_title_raw = analyser._room_pos_to_title_map[
|
||||
room_pos
|
||||
]
|
||||
if old_title != room_title or old_title_raw != room_title_raw:
|
||||
analyser._room_pos_to_title_map[room_pos] = (
|
||||
room_title,
|
||||
@@ -231,7 +244,9 @@ class ReservationHandler:
|
||||
log_type="OP",
|
||||
room_pos=room_pos,
|
||||
old_room_title=old_title[:50] if old_title else "",
|
||||
new_room_title=room_title[:50] if room_title else "",
|
||||
new_room_title=(
|
||||
room_title[:50] if room_title else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -241,7 +256,9 @@ class ReservationHandler:
|
||||
# 如果读取标题失败,尝试使用缓存的标题
|
||||
try:
|
||||
room_title = str(getattr(analyser, "current_room_title", "") or "")
|
||||
room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "")
|
||||
room_title_raw = str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
)
|
||||
if room_title or room_title_raw:
|
||||
analyser._room_pos_to_title_map[room_pos] = (
|
||||
room_title,
|
||||
@@ -348,9 +365,7 @@ class ReservationHandler:
|
||||
pass
|
||||
elif pos_diff < 0:
|
||||
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
|
||||
back_times = (
|
||||
min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
|
||||
)
|
||||
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
@@ -673,7 +688,9 @@ class ReservationHandler:
|
||||
|
||||
# 再次检测按钮状态,验证是否参与成功
|
||||
try:
|
||||
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
|
||||
analyser.operation.get_screenshot(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
screenshot_path2 = path_config.get_screenshot_path()
|
||||
pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined]
|
||||
button_result2 = douyin_pixel.detect_attend_button_red_area(
|
||||
|
||||
@@ -556,11 +556,36 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
# 计算各阶段耗时(可能为 None)
|
||||
screenshot_ms = (
|
||||
round((screenshot_end - screenshot_start) * 1000, 1)
|
||||
if screenshot_start is not None and screenshot_end is not None
|
||||
else None
|
||||
)
|
||||
ocr_ms = (
|
||||
round((ocr_end - ocr_start) * 1000, 1)
|
||||
if ocr_start is not None and ocr_end is not None
|
||||
else None
|
||||
)
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once完成(成功)",
|
||||
log_type="OP",
|
||||
level="INFO",
|
||||
elapsed_seconds=round(elapsed, 2),
|
||||
level="DEBUG",
|
||||
screenshot_ms=screenshot_ms,
|
||||
ocr_ms=ocr_ms,
|
||||
wait_file_ms=wait_file_ms,
|
||||
image_load_ms=image_load_ms,
|
||||
service_stop_ms=service_stop_ms,
|
||||
countdown_parse_ms=countdown_parse_ms,
|
||||
screenshot_reused=bool(getattr(analyser, "_screenshot_ready_for_ocr", False)),
|
||||
content_preview=(content or "")[:60],
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
time_text=time_text or "",
|
||||
participants=int(participants or 0),
|
||||
copies=int(copies or 0),
|
||||
task_count=task_count,
|
||||
)
|
||||
_log_perf("success")
|
||||
return "ok", detail_tuple, extra
|
||||
|
||||
@@ -9,6 +9,9 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Tuple
|
||||
import re
|
||||
import os
|
||||
import json
|
||||
import path_config
|
||||
|
||||
|
||||
def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, str]:
|
||||
@@ -46,8 +49,31 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
pass
|
||||
|
||||
# 检查1:内容不能为空(至少要有一些文字)
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
# 如果运行时显式禁用了内容识别,则跳过此检查(允许内容为空)
|
||||
try:
|
||||
disable_content = False
|
||||
if analyser:
|
||||
disable_content = bool(
|
||||
getattr(analyser, "fudai_disable_content_recognition", False)
|
||||
)
|
||||
# 如果 analyser 未设置该属性,再尝试从 config.json 读取全局配置
|
||||
if not disable_content:
|
||||
try:
|
||||
cfg_path = path_config.get_config_path()
|
||||
if cfg_path and os.path.exists(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
disable_content = bool(
|
||||
cfg.get("fudai_disable_content_recognition", False)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if not disable_content:
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
except Exception:
|
||||
if not content or len(content.strip()) < 2:
|
||||
return False, "content_empty_or_too_short"
|
||||
|
||||
# 检查2:价值应该大于0(福袋至少应该有价值)
|
||||
if prize_value_yuan <= 0:
|
||||
@@ -73,7 +99,9 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
# 注意:如果analyser存在且处于强制参与模式(预约回退),跳过此检查
|
||||
force_attend = False
|
||||
if analyser:
|
||||
force_attend = getattr(analyser, "_force_attend_after_reservation_back", False)
|
||||
force_attend = getattr(
|
||||
analyser, "_force_attend_after_reservation_back", False
|
||||
)
|
||||
|
||||
if time_text and not force_attend:
|
||||
try:
|
||||
@@ -92,9 +120,14 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
text_seconds = mm * 60 + ss
|
||||
# 允许一定误差(±10%),但差异过大则判定为识别错误
|
||||
if text_seconds > 0:
|
||||
diff_ratio = abs(remain_seconds - text_seconds) / max(text_seconds, 1.0)
|
||||
diff_ratio = abs(remain_seconds - text_seconds) / max(
|
||||
text_seconds, 1.0
|
||||
)
|
||||
if diff_ratio > 0.15: # 差异超过15%视为不一致
|
||||
return False, f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)"
|
||||
return (
|
||||
False,
|
||||
f"countdown_mismatch_time_text (remain={int(remain_seconds)}, text={text_seconds}, diff={round(diff_ratio*100, 1)}%)",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
+42
-17
@@ -7,11 +7,28 @@ import sys
|
||||
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
# 日志配置失败不影响主流程,但会缺少文件日志
|
||||
pass
|
||||
|
||||
# 尝试确保行为日志的异步 listener 在进程启动时就被启动,
|
||||
# 以避免某些运行环境中模块未完整初始化导致日志未落盘的问题。
|
||||
try:
|
||||
# 直接以模块方式导入,避免 package 的 `__init__` 导出遮蔽(`from douyin.logging import action_logger`
|
||||
# 会失败因为 package 只导出了 `ActionLogger` 等名字)。
|
||||
import importlib
|
||||
|
||||
action_logger_mod = importlib.import_module("douyin.logging.action_logger")
|
||||
try:
|
||||
action_logger_mod._start_queue_listener_if_needed()
|
||||
except Exception:
|
||||
# 启动失败时不影响主流程,action_logger 有回退到同步 file handler 的逻辑
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
|
||||
# 当前 WebGUI 目录中没有完整版 douyin_fudai.py,而是在 Cursor 的工作树中存在完整实现。
|
||||
# 同时,我们在本目录下放置了一些 shim 模块(如 douyin_text_utils、douyin_swipe_ops 等),
|
||||
@@ -22,12 +39,8 @@ _BASE_DIR = os.path.dirname(__file__)
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(
|
||||
os.path.expanduser("~"),
|
||||
".cursor",
|
||||
"worktrees",
|
||||
"douyin_guaji-main",
|
||||
"axf"
|
||||
)
|
||||
os.path.expanduser("~"), ".cursor", "worktrees", "douyin_guaji-main", "axf"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -53,7 +66,9 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
|
||||
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
|
||||
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
|
||||
_load_local_shim("douyin_reservation_ops", "douyin/reservation/douyin_reservation_ops.py")
|
||||
_load_local_shim(
|
||||
"douyin_reservation_ops", "douyin/reservation/douyin_reservation_ops.py"
|
||||
)
|
||||
|
||||
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
|
||||
try:
|
||||
@@ -295,13 +310,15 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
try:
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_btn_x", 540), getattr(analyser, "yanghao_comment_btn_y", 2000)
|
||||
getattr(analyser, "yanghao_comment_btn_x", 540),
|
||||
getattr(analyser, "yanghao_comment_btn_y", 2000),
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_open")
|
||||
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_input_x", 540), getattr(analyser, "yanghao_comment_input_y", 1900)
|
||||
getattr(analyser, "yanghao_comment_input_x", 540),
|
||||
getattr(analyser, "yanghao_comment_input_y", 1900),
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_focus")
|
||||
@@ -321,7 +338,8 @@ def main(argv: list[str]) -> int:
|
||||
analyser._save_step_screenshot("test_comment_after_send")
|
||||
|
||||
_scaled_click(
|
||||
getattr(analyser, "yanghao_comment_close_x", 900), getattr(analyser, "yanghao_comment_close_y", 300)
|
||||
getattr(analyser, "yanghao_comment_close_x", 900),
|
||||
getattr(analyser, "yanghao_comment_close_y", 300),
|
||||
)
|
||||
analyser.operation.delay(1)
|
||||
analyser._save_step_screenshot("test_comment_after_close")
|
||||
@@ -368,10 +386,15 @@ def main(argv: list[str]) -> int:
|
||||
analyser.skip_if_countdown_gt_seconds = int(
|
||||
args.skip_if_countdown_gt_seconds or 900
|
||||
)
|
||||
if hasattr(args, 'skip_if_countdown_lt_seconds') and args.skip_if_countdown_lt_seconds is not None:
|
||||
setattr(analyser, "skip_if_countdown_lt_seconds", int(
|
||||
args.skip_if_countdown_lt_seconds or 10
|
||||
))
|
||||
if (
|
||||
hasattr(args, "skip_if_countdown_lt_seconds")
|
||||
and args.skip_if_countdown_lt_seconds is not None
|
||||
):
|
||||
setattr(
|
||||
analyser,
|
||||
"skip_if_countdown_lt_seconds",
|
||||
int(args.skip_if_countdown_lt_seconds or 10),
|
||||
)
|
||||
if args.reset_after_swipes is not None:
|
||||
analyser.reset_after_swipes = max(1, int(args.reset_after_swipes or 0))
|
||||
analyser.reset_after_swipes_enabled = True
|
||||
@@ -398,9 +421,11 @@ def main(argv: list[str]) -> int:
|
||||
# 运行时覆盖:回退后滑动等待(快速值,仅在未启用回退校验时使用)
|
||||
if getattr(args, "reservation_back_swipe_delay", None) is not None:
|
||||
try:
|
||||
setattr(analyser, "reservation_back_swipe_delay_fast_seconds", float(
|
||||
args.reservation_back_swipe_delay
|
||||
))
|
||||
setattr(
|
||||
analyser,
|
||||
"reservation_back_swipe_delay_fast_seconds",
|
||||
float(args.reservation_back_swipe_delay),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if getattr(args, "reservation_preempt_min_value", None) is not None:
|
||||
|
||||
Reference in new issue
Block a user