feat: Enhance logging and parameter tracking capabilities
- Refactor `gui_core.py` to improve code readability and maintainability by adding line breaks for long statements. - Introduce `inspect_lines.py` script for inspecting specific line ranges in files. - Add `generate_param_locations.py` to scan the repository and generate a report of function definitions, argparse parameters, and tracking calls. - Implement `param_usage_tool.py` for analyzing `param_usage.json` records and scanning code for tracking calls. - Create `simulate_reservation_preempted_flow.py` and `simulate_reservation_preempted_flow_dynamic.py` to validate behavior of reservation logic under specific conditions. - Add global parameter tracking feature in `run_cli.py` to enable detailed usage tracing.
This commit is contained in:
1 parent
68c8ccea66
commit
95b4517bdd
23 files changed
+1560
-849
No files matched your search
+117
-31
@@ -262,9 +262,7 @@ def main():
|
||||
# 创建日志写入器实例
|
||||
log_writer = ThreadSafeLogWriter()
|
||||
|
||||
"""
|
||||
日志格式化已移至模块级别函数 format_gui_log_line()
|
||||
"""
|
||||
# 日志格式化已移至模块级别函数 format_gui_log_line()
|
||||
|
||||
def on_line(line: str):
|
||||
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
|
||||
@@ -2057,8 +2055,7 @@ def main():
|
||||
def screenshot_thread():
|
||||
try:
|
||||
from Underlying_Operations import underlying_operations
|
||||
from PIL import Image
|
||||
import os
|
||||
# 使用模块级别导入的 Image 与 os,避免重复导入导致 Pylance 警告
|
||||
|
||||
# 使用 root.after 在主线程中更新日志
|
||||
def log_msg(msg: str) -> Callable[[], None]:
|
||||
@@ -2214,6 +2211,7 @@ def main():
|
||||
reservation_tab = ttk.Frame(notebook)
|
||||
high_value_tab = ttk.Frame(notebook)
|
||||
actions_log_tab = ttk.Frame(notebook)
|
||||
realtime_tab = ttk.Frame(notebook)
|
||||
ocr_results_tab = ttk.Frame(notebook)
|
||||
win_record_tab = ttk.Frame(notebook)
|
||||
notebook.add(log_tab, text="运行日志")
|
||||
@@ -2222,6 +2220,7 @@ def main():
|
||||
notebook.add(reservation_tab, text="预约队列")
|
||||
notebook.add(high_value_tab, text="高价值房间")
|
||||
notebook.add(actions_log_tab, text="行为日志")
|
||||
notebook.add(realtime_tab, text="实时状态")
|
||||
notebook.add(ocr_results_tab, text="OCR结果")
|
||||
notebook.add(win_record_tab, text="中奖记录")
|
||||
|
||||
@@ -2229,6 +2228,109 @@ def main():
|
||||
log_box = ttk.Frame(log_tab)
|
||||
log_box.pack(fill=BOTH, expand=True)
|
||||
|
||||
# ========== 实时状态 Tab(显示最近动作 + 耗时) ==========
|
||||
try:
|
||||
realtime_frame = ttk.Frame(realtime_tab)
|
||||
realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8)
|
||||
|
||||
realtime_text = ScrolledText(realtime_frame, height=20)
|
||||
realtime_text.pack(fill=BOTH, expand=True)
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# re 已在模块顶部导入,避免重复导入
|
||||
|
||||
realtime_after_id = None
|
||||
|
||||
def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]:
|
||||
"""从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
with open(path, "rb") as f:
|
||||
f.seek(0, os.SEEK_END)
|
||||
file_size = f.tell()
|
||||
seek_from = max(0, file_size - max_bytes)
|
||||
f.seek(seek_from)
|
||||
data = f.read()
|
||||
text = data.decode(errors="ignore")
|
||||
# splitlines 保留不含尾部换行的处理
|
||||
return text.splitlines()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def parse_action_duration(line: str) -> tuple[str, str] | None:
|
||||
"""从一行日志提取 (action, duration),未找到返回 None。"""
|
||||
if "耗时" not in line:
|
||||
return None
|
||||
# 尝试提取耗时数字
|
||||
m = re.search(r"耗时[:=]?\s*([0-9]+(?:\.[0-9]+)?)\s*s", line)
|
||||
dur = None
|
||||
if m:
|
||||
dur = m.group(1) + "s"
|
||||
else:
|
||||
m2 = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*s", line)
|
||||
if m2:
|
||||
dur = m2.group(1) + "s"
|
||||
|
||||
if not dur:
|
||||
return None
|
||||
|
||||
# 动作名取耗时之前的文本片段,最多保留 60 字符
|
||||
idx = line.find("耗时")
|
||||
action = line[:idx].strip()
|
||||
if not action:
|
||||
# 兜底:取整行前 60 字符
|
||||
action = line.strip()[:60]
|
||||
if len(action) > 60:
|
||||
action = action[:57] + "..."
|
||||
return (action, dur)
|
||||
|
||||
def refresh_realtime_tab():
|
||||
nonlocal realtime_after_id
|
||||
cfg = read_config()
|
||||
gui_cfg = cfg.get("gui", {}).get("realtime_status", {})
|
||||
refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000))
|
||||
tail_items = int(gui_cfg.get("tail_items", 50))
|
||||
|
||||
path = os.path.join(get_logs_dir(), "actions.log")
|
||||
lines = tail_read_file(path)
|
||||
parsed: list[tuple[str, str]] = []
|
||||
# 从文件末尾向前解析,保持原始顺序输出最近项
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
out = parse_action_duration(line)
|
||||
if out:
|
||||
parsed.append(out)
|
||||
if len(parsed) >= tail_items:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
parsed = list(reversed(parsed))
|
||||
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
if not parsed:
|
||||
realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)")
|
||||
else:
|
||||
for action, dur in parsed:
|
||||
realtime_text.insert("end", f"{action} {dur}\n")
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# 安排下一次刷新
|
||||
try:
|
||||
realtime_after_id = root.after(refresh_ms, refresh_realtime_tab)
|
||||
except Exception:
|
||||
realtime_after_id = None
|
||||
|
||||
# 启动刷新(仅在 Tab 被创建时启动)
|
||||
try:
|
||||
refresh_realtime_tab()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 搜索工具栏
|
||||
log_search_frame = ttk.Frame(log_box)
|
||||
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
|
||||
@@ -2811,12 +2913,10 @@ def main():
|
||||
|
||||
last_log_ts = stats.get("last_log_ts")
|
||||
if last_log_ts:
|
||||
import datetime
|
||||
|
||||
dt = datetime.datetime.fromtimestamp(last_log_ts)
|
||||
lines.append(f"最近日志时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
dt = datetime.fromtimestamp(last_log_ts)
|
||||
lines.append("最近日志时间: " + dt.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
else:
|
||||
lines.append(f"最近日志时间: -")
|
||||
lines.append("最近日志时间: -")
|
||||
|
||||
exit_code = stats.get("exit_code")
|
||||
lines.append(f"退出码: {exit_code if exit_code is not None else '-'}")
|
||||
@@ -3433,10 +3533,8 @@ def main():
|
||||
lines.append(f"奖品价值: {prize_value} 元")
|
||||
updated_ts = fudai_last.get("updated_ts")
|
||||
if updated_ts:
|
||||
import datetime
|
||||
|
||||
dt = datetime.datetime.fromtimestamp(updated_ts)
|
||||
lines.append(f"更新时间: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
dt = datetime.fromtimestamp(updated_ts)
|
||||
lines.append("更新时间: " + dt.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
lines.append("")
|
||||
|
||||
# 中奖记录
|
||||
@@ -3446,13 +3544,9 @@ def main():
|
||||
lines.append(f"最近中奖记录(显示最近 {len(wins)} 条)")
|
||||
lines.append("=" * 60)
|
||||
for i, win in enumerate(wins[-10:], 1): # 只显示最近10条
|
||||
import datetime
|
||||
|
||||
ts = win.get("ts", 0)
|
||||
dt_str = (
|
||||
datetime.datetime.fromtimestamp(ts).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if ts
|
||||
else "-"
|
||||
)
|
||||
@@ -3514,8 +3608,6 @@ def main():
|
||||
data = json.load(f)
|
||||
reservation_text.delete("1.0", "end")
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
updated_ts = (
|
||||
float(data.get("updated_ts", 0.0) or 0.0)
|
||||
if isinstance(data, dict)
|
||||
@@ -3710,13 +3802,13 @@ def main():
|
||||
|
||||
# 格式化显示
|
||||
lines.append(
|
||||
f"┌─ 预约 #{idx} ─────────────────────────────────────────────"
|
||||
"┌─ 预约 #" + str(idx) + " ─────────────────────────────────────────────"
|
||||
)
|
||||
lines.append(f"│ 状态:{status_icon} {remain_str}")
|
||||
lines.append(f"│")
|
||||
lines.append("│")
|
||||
lines.append(f"│ 💰 奖品价值:{val:.2f} 元")
|
||||
lines.append(f"│ 📦 奖品内容:{content or '(无描述)'}")
|
||||
lines.append(f"│")
|
||||
lines.append("│")
|
||||
lines.append(f"│ ⏰ 预计开奖时间:{ft_str or '未知'}")
|
||||
if ft > 0:
|
||||
try:
|
||||
@@ -3728,7 +3820,7 @@ def main():
|
||||
lines.append(f"│ 详细时间:{ft_str_detailed}")
|
||||
except Exception:
|
||||
pass
|
||||
lines.append(f"│")
|
||||
lines.append("│")
|
||||
lines.append(
|
||||
f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})"
|
||||
)
|
||||
@@ -4213,8 +4305,6 @@ def main():
|
||||
for idx, (file, file_path, mtime) in enumerate(win_images):
|
||||
# 格式化显示:文件名 + 时间
|
||||
try:
|
||||
from datetime import datetime
|
||||
|
||||
dt = datetime.fromtimestamp(mtime)
|
||||
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
display_text = f"{file} ({time_str})"
|
||||
@@ -4338,8 +4428,6 @@ def main():
|
||||
return
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
with open(false_positive_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
false_positives = data.get("false_positives", [])
|
||||
@@ -4372,8 +4460,6 @@ def main():
|
||||
lines = [line.strip() for line in content.splitlines() if line.strip()]
|
||||
|
||||
try:
|
||||
import json
|
||||
|
||||
with open(false_positive_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
|
||||
on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
|
||||
|
||||
Reference in new issue
Block a user