feat: Add logging and error handling enhancements

- Introduced new logging modules for action tracking, error logging, and performance tracking to improve observability.
- Added functions for retrieving debug and error log paths in `path_config.py`.
- Updated various components to utilize the new logging system, enhancing error handling and performance diagnostics.
- Implemented a GUI component for viewing error logs, improving user experience in monitoring application issues.
- Cleaned up unnecessary blank lines and improved code readability across multiple files.
This commit is contained in:
Your Name committed 2025-12-29 20:48:09 +08:00
1 parent bdf9312bc9
commit efe6e2252f
48 files changed
+2165 -320

No files matched your search

+377 -77
View File
@@ -32,7 +32,83 @@ warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning
warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning)
def format_gui_log_line(line: str) -> str:
"""
将完整日志行转换为GUI显示用的精简版本。
使用新的日志格式化模块进行美化和格式化处理。
"""
try:
# 尝试使用新的日志格式化模块
from gui.components.log_viewer import format_gui_log_line as enhanced_formatter
return enhanced_formatter(line)
except ImportError:
# 如果新模块不可用,回退到原来的实现
pass
# 回退到原来的精简规则(兼容统一日志格式)
s = (line or "").rstrip("\n")
if not s:
return s
ts_part: str | None = None
msg_part: str | None = None
# 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...
m = re.match(r"^\[(\d{4}-\d{2}-\d{2} [0-9:.]+)\]\s+\[[A-Z]+\]\s+(.*)$", s)
if m:
ts_part = m.group(1).strip()
msg_part = m.group(2).strip()
# 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容
elif s[0].isdigit() and " - " in s:
parts = s.split(" - ")
if len(parts) >= 3:
ts_part = parts[0].strip()
msg_part = parts[-1].strip()
# 如果没解析出时间戳和消息,返回原字符串
if not ts_part or msg_part is None:
return s
# 从业务文案中拆分出字段_xxx=yyy,非score类字段在GUI中隐藏
keep_tokens: list[str] = []
def _is_score_field(k: str) -> bool:
kl = k.lower()
return (
"score" in kl
or "match" in kl
or "匹配" in k
or "相似" in k
)
# 解析字段
words = msg_part.split()
clean_words = []
for word in words:
if "=" in word:
k, v = word.split("=", 1)
if _is_score_field(k):
keep_tokens.append(word)
# else: 其他字段在GUI中隐藏
else:
clean_words.append(word)
clean_msg = " ".join(clean_words)
if keep_tokens:
clean_msg = f"{clean_msg} ({', '.join(keep_tokens)})"
return f"{ts_part} {clean_msg}"
def main():
# 主题优先级:使用 config 中的 gui.theme(若有),否则使用默认明亮主题 'litera'
cfg_theme = "darkly"
try:
cfg_theme = read_config().get("gui", {}).get("theme", "litera") or "litera"
except Exception:
cfg_theme = "litera"
# ttkbootstrap 优先(更美观);没装则回退到原生 tkinter
try:
import ttkbootstrap as tb
@@ -42,7 +118,8 @@ def main():
from tkinter import ttk
from ttkbootstrap.constants import LEFT, RIGHT, BOTH, X, Y
root = tb.Window(themename="darkly")
# 使用 config 中指定的主题名
root = tb.Window(themename=cfg_theme)
except Exception:
import tkinter as tk
from tkinter import ttk
@@ -170,81 +247,15 @@ def main():
# 创建日志写入器实例
log_writer = ThreadSafeLogWriter()
def _format_gui_log_line(line: str) -> str:
"""
将“完整日志行”转换为 GUI 显示用的精简版本。
需求:
- 文件中:仍然写入完整统一日志(含时间戳 / 级别 / 模块等信息);
- GUI 中:保留【时间戳 + 业务日志】;
- 如果该行包含识别/匹配的分数(如 `匹配度=0.87` / `相似度=0.95` / `score=0.83`),
需要在 GUI 文本中一并保留/补充出来。
精简规则(兼容统一日志格式):
- 统一日志通常形如:
YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - [线程] - [模块:函数:行号] - [traceId:xxx] - 业务内容
- GUI 只展示:
YYYY-MM-DD HH:MM:SS.xxx 业务内容(末尾可追加“(匹配度=..., 相似度=..., score=...)”)
- 其他不符合该模式的行保持原样。
"""
s = (line or "").rstrip("\n")
if not s:
return s
ts_part: str | None = None
msg_part: str | None = None
# 1)新统一日志格式:[YYYY-MM-DD HH:MM:SS.xxx] [LEVEL] ... 业务内容 字段_xxx=...
m = re.match(r"^\[(\d{4}-\d{2}-\d{2} [0-9:.]+)\]\s+\[[A-Z]+\]\s+(.*)$", s)
if m:
ts_part = m.group(1).strip()
msg_part = m.group(2).strip()
# 2)旧统一日志格式:YYYY-MM-DD HH:MM:SS.xxx - [LEVEL] - ... - 业务内容
elif s[0].isdigit() and " - " in s:
parts = s.split(" - ")
if len(parts) >= 3:
ts_part = parts[0].strip()
msg_part = parts[-1].strip()
# 如果没解析出“时间戳 + 业务文案”,原样返回
if not ts_part or msg_part is None:
return s
# 从业务文案中拆分出 字段_xxx=yyy,非 score 类字段在 GUI 中隐藏
keep_tokens: list[str] = []
def _is_score_field(k: str) -> bool:
kl = k.lower()
return (
"score" in kl
or "match" in kl
or "匹配" in k
or "相似" in k
)
for m2 in re.finditer(r"字段_([^\s=]+)=([^\s]+)", msg_part):
key = m2.group(1)
val = m2.group(2)
if _is_score_field(key):
keep_tokens.append(f"{key}={val}")
# 先把所有 字段_xxx=yyy 从业务文案中移除
clean_msg = re.sub(r"\s*字段_[^\s=]+=[^\s]+", "", msg_part).strip()
# 追加需要展示的分数字段
if keep_tokens:
clean_msg = f"{clean_msg} ({', '.join(keep_tokens)})"
return f"{ts_part} {clean_msg}"
# 不符合“完整格式”的行,原样返回
return s
"""
日志格式化已移至模块级别函数 format_gui_log_line()
"""
def on_line(line: str):
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
# GUI 显示:使用精简后的版本
try:
display_line = _format_gui_log_line(line)
display_line = format_gui_log_line(line)
except Exception:
display_line = line
q.put(display_line)
@@ -548,6 +559,34 @@ def main():
)
)
# 日志配置变量
logging_beautify_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("beautify_output", True))
)
logging_color_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("color_output", True))
)
logging_show_timestamps_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("show_timestamps", True))
)
logging_performance_enabled_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True))
)
logging_track_functions_var = tk.BooleanVar(
value=bool(cfg.get("logging", {}).get("performance_tracking", {}).get("track_function_calls", True))
)
logging_debug_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("debug_detail_level", "normal"))
)
logging_error_level_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("error_detail_level", "full"))
)
logging_action_format_var = tk.StringVar(
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
)
# GUI 主题变量
gui_theme_var = tk.StringVar(value=str(cfg.get("gui", {}).get("theme", "litera") or "litera"))
# 倒计时小于阈值参数
skip_lt_seconds_var = tk.IntVar(
value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)
@@ -894,10 +933,39 @@ def main():
# 标签页5:调试参数
debug_tab = ttk.Frame(left_notebook)
# 为调试参数标签页添加滚动条
debug_canvas = tk.Canvas(debug_tab, highlightthickness=0)
debug_scrollbar = ttk.Scrollbar(debug_tab, orient="vertical", command=debug_canvas.yview)
debug_scrollable_frame = ttk.Frame(debug_canvas)
debug_scrollable_frame.bind(
"<Configure>",
lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all"))
)
debug_canvas.create_window((0, 0), window=debug_scrollable_frame, anchor="nw")
debug_canvas.configure(yscrollcommand=debug_scrollbar.set)
# 鼠标滚轮支持
def _on_mousewheel(event):
debug_canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def _on_shift_mousewheel(event):
debug_canvas.xview_scroll(int(-1*(event.delta/120)), "units")
debug_canvas.bind_all("<MouseWheel>", _on_mousewheel)
debug_canvas.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
debug_canvas.pack(side="left", fill="both", expand=True)
debug_scrollbar.pack(side="right", fill="y")
left_notebook.add(debug_tab, text="调试参数")
# 使用scrollable_frame作为容器
debug_container = debug_scrollable_frame
# 调试图像
debug_captures_box = ttk.LabelFrame(debug_tab, text="调试图像")
debug_captures_box = ttk.LabelFrame(debug_container, text="调试图像")
debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))
debug_r0 = ttk.Frame(debug_captures_box)
@@ -908,7 +976,7 @@ def main():
variable=debug_captures_enabled_var,
).pack(side=LEFT)
debug_cleanup_box = ttk.LabelFrame(debug_tab, text="调试图像清理")
debug_cleanup_box = ttk.LabelFrame(debug_container, text="调试图像清理")
debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))
debug_r1 = ttk.Frame(debug_cleanup_box)
@@ -940,7 +1008,7 @@ def main():
ttk.Label(debug_r2, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
# 找福袋参数
fudai_find_box = ttk.LabelFrame(debug_tab, text="找福袋参数")
fudai_find_box = ttk.LabelFrame(debug_container, text="找福袋参数")
fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))
row4 = ttk.Frame(fudai_find_box)
@@ -1033,7 +1101,7 @@ def main():
)
# 阶段诊断时间参数(用于调试)
diag_time_box = ttk.LabelFrame(debug_tab, text="阶段诊断时间参数")
diag_time_box = ttk.LabelFrame(debug_container, text="阶段诊断时间参数")
diag_time_box.pack(fill=X, padx=10, pady=(0, 10))
diag_time_r1 = ttk.Frame(diag_time_box)
diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))
@@ -1128,7 +1196,7 @@ def main():
)
# 像素检测阈值
pixel_detect_box = ttk.LabelFrame(debug_tab, text="像素检测阈值")
pixel_detect_box = ttk.LabelFrame(debug_container, text="像素检测阈值")
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
pixel_r1 = ttk.Frame(pixel_detect_box)
@@ -1161,6 +1229,90 @@ 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))
# 日志美化选项
log_r1 = ttk.Frame(logging_config_box)
log_r1.pack(fill=X, padx=10, pady=(10, 6))
ttk.Checkbutton(
log_r1,
text="启用日志美化",
variable=logging_beautify_var,
).pack(side=LEFT)
ttk.Checkbutton(
log_r1,
text="启用颜色显示",
variable=logging_color_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,
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)
ttk.Combobox(
log_theme_row,
values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"],
textvariable=gui_theme_var,
state="readonly",
width=12
).pack(side=LEFT, padx=(6, 0))
ttk.Label(log_theme_row, text="(更改后请保存并重启以完全应用主题)").pack(side=LEFT, padx=(12,0))
# 性能追踪
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))
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)
# 标签页6:关键词
keywords_tab = ttk.Frame(left_notebook)
left_notebook.add(keywords_tab, text="关键词")
@@ -1254,6 +1406,11 @@ def main():
switch_room_wait_after_stage_diag_seconds_var.set(
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
)
# GUI 主题
try:
gui_theme_var.set(str(cfg.get("gui", {}).get("theme", "litera") or "litera"))
except Exception:
gui_theme_var.set("litera")
live_room_match_threshold_var.set(
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
)
@@ -1503,6 +1660,22 @@ def main():
debug_captures_max_files_var.get() or 2000
)
# 日志配置
if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict):
cfg2["logging"] = {}
cfg2["logging"]["beautify_output"] = bool(logging_beautify_var.get())
cfg2["logging"]["color_output"] = bool(logging_color_var.get())
cfg2["logging"]["show_timestamps"] = bool(logging_show_timestamps_var.get())
cfg2["logging"]["debug_detail_level"] = str(logging_debug_level_var.get() or "normal")
cfg2["logging"]["error_detail_level"] = str(logging_error_level_var.get() or "full")
cfg2["logging"]["action_log_format"] = str(logging_action_format_var.get() or "concise")
# 性能追踪配置
if "performance_tracking" not in cfg2["logging"] or not isinstance(cfg2["logging"]["performance_tracking"], dict):
cfg2["logging"]["performance_tracking"] = {}
cfg2["logging"]["performance_tracking"]["enabled"] = bool(logging_performance_enabled_var.get())
cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(logging_track_functions_var.get())
cfg2["yanghao_enabled"] = bool(yg_enabled_var.get())
cfg2["yanghao_enable_actions"] = bool(yg_actions_enabled_var.get())
cfg2["yanghao_recommend_duration_seconds"] = int(
@@ -1550,6 +1723,12 @@ def main():
cfg2["yanghao_comment_texts"] = yg_comment_text_lines
cfg2["yanghao_like_keywords"] = yg_like_kw_lines
cfg2["yanghao_fav_keywords"] = yg_fav_kw_lines
# GUI 配置
if "gui" not in cfg2 or not isinstance(cfg2["gui"], dict):
cfg2["gui"] = {}
cfg2["gui"]["theme"] = str(gui_theme_var.get() or "litera")
write_config(cfg2)
on_line("[配置] 已保存到 config.json")
@@ -1892,6 +2071,38 @@ def main():
pass
log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
# 配置日志颜色标签(如果支持颜色)
try:
# 根据主题调整日志颜色(明亮主题使用深色文字/蓝色系)
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
try:
current_theme = str(gui_theme_var.get() or "litera")
except Exception:
current_theme = "litera"
if current_theme in light_themes:
# 明亮主题 - 使用更适合人眼观看的颜色组合
log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C")
log_text.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色
log_text.tag_configure("log_info", foreground="#1E88E5") # 明亮的蓝色,易于阅读
log_text.tag_configure("log_warning", foreground="#F57C00") # 橙色,警告色但不过于刺眼
log_text.tag_configure("log_error", foreground="#D32F2F") # 深红色,醒目但不刺眼
log_text.tag_configure("log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")) # 加粗深红色
log_text.tag_configure("log_performance", foreground="#388E3C") # 深绿色,性能指标
log_text.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识
else:
# 暗色主题 - 优化对比度和可读性
log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF")
log_text.tag_configure("log_timestamp", foreground="#A0A0A0") # 浅灰色时间戳
log_text.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级
log_text.tag_configure("log_warning", foreground="#FFB74D") # 金色警告,暗色背景下醒目
log_text.tag_configure("log_error", foreground="#EF5350") # 亮红色,错误突出
log_text.tag_configure("log_critical", foreground="#F44336", font=("Consolas", 10, "bold")) # 加粗亮红色
log_text.tag_configure("log_performance", foreground="#81C784") # 亮绿色,性能数据
log_text.tag_configure("log_module", foreground="#BA68C8") # 亮紫色,模块标识
except Exception:
pass # 忽略标签配置失败
# 截图预览
preview_top = ttk.Frame(preview_tab)
preview_top.pack(fill=X, padx=10, pady=10)
@@ -2214,7 +2425,35 @@ def main():
while True:
line = q.get_nowait()
try:
# 插入日志行并应用颜色标签
start_pos = log_text.index("end-1c")
# 检查是否需要应用颜色标签
tag = None
if "[INFO]" in line:
tag = "log_info"
elif "[WARNING]" in line:
tag = "log_warning"
elif "[ERROR]" in line:
tag = "log_error"
elif "[CRITICAL]" in line:
tag = "log_critical"
elif "elapsed_seconds=" in line or "耗时" in line:
tag = "log_performance"
elif re.search(r'\[[\w\.]+\]', line):
tag = "log_module"
# 插入文本
log_text.insert("end", line + "\n")
# 如果有标签,应用到这一行
if tag:
end_pos = log_text.index("end-1c")
try:
log_text.tag_add(tag, start_pos, end_pos)
except Exception:
pass # 忽略标签应用失败
# 不再自动滚动到底部,让用户自由控制滚动位置
changed = True
except Exception as e:
@@ -3191,6 +3430,36 @@ def main():
except Exception:
pass
# 配置行为日志颜色标签(与主日志保持一致)
try:
# 根据主题调整行为日志颜色
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
try:
current_theme = str(gui_theme_var.get() or "litera")
except Exception:
current_theme = "litera"
if current_theme in light_themes:
# 明亮主题
actions_log_text.configure(background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C")
actions_log_text.tag_configure("action_timestamp", foreground="#8B8B8B")
actions_log_text.tag_configure("action_operation", foreground="#1E88E5") # 蓝色操作
actions_log_text.tag_configure("action_ocr", foreground="#388E3C") # 绿色OCR
actions_log_text.tag_configure("action_decision", foreground="#F57C00") # 橙色决策
actions_log_text.tag_configure("action_state", foreground="#7B1FA2") # 紫色状态
actions_log_text.tag_configure("action_performance", foreground="#D32F2F") # 红色性能
else:
# 暗色主题
actions_log_text.configure(background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF")
actions_log_text.tag_configure("action_timestamp", foreground="#A0A0A0")
actions_log_text.tag_configure("action_operation", foreground="#64B5F6") # 亮蓝色操作
actions_log_text.tag_configure("action_ocr", foreground="#81C784") # 亮绿色OCR
actions_log_text.tag_configure("action_decision", foreground="#FFB74D") # 金色决策
actions_log_text.tag_configure("action_state", foreground="#BA68C8") # 亮紫色状态
actions_log_text.tag_configure("action_performance", foreground="#EF5350") # 亮红色性能
except Exception:
pass # 忽略颜色配置失败
actions_filter_var = tk.StringVar(value="")
def refresh_actions_log():
@@ -3246,7 +3515,38 @@ def main():
actions_log_text.delete("1.0", "end")
if tail:
actions_log_text.insert("1.0", "\n".join(tail))
# 逐行插入并应用颜色标签
for i, line in enumerate(tail):
start_pos = actions_log_text.index("end-1c")
# 插入行内容
if i > 0:
actions_log_text.insert("end", "\n")
actions_log_text.insert("end", line)
# 根据内容类型应用颜色标签
end_pos = actions_log_text.index("end")
tag = None
if "操作:" in line or "执行" in line:
tag = "action_operation"
elif "OCR" in line or "识别" in line:
tag = "action_ocr"
elif "决策" in line or "判断" in line:
tag = "action_decision"
elif "状态" in line or "阶段" in line:
tag = "action_state"
elif "耗时" in line or "时间" in line or "性能" in line:
tag = "action_performance"
elif re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', line):
tag = "action_timestamp"
# 应用标签
if tag:
try:
actions_log_text.tag_add(tag, start_pos, end_pos)
except Exception:
pass # 忽略标签应用失败
else:
actions_log_text.insert("1.0", "暂无匹配的行为日志")