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:
1 parent
bdf9312bc9
commit
efe6e2252f
48 files changed
+2165
-320
No files matched your search
@@ -11,3 +11,9 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -51,3 +51,9 @@ def save_ui_to_config(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -61,3 +61,9 @@ def create_device_selector(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""错误日志查看界面 - 专门用于显示错误日志的组件"""
|
||||
from __future__ import annotations
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
import os
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime, timedelta
|
||||
import re
|
||||
|
||||
try:
|
||||
from path_config import get_error_log_path
|
||||
HAS_LOGGING = True
|
||||
except ImportError:
|
||||
HAS_LOGGING = False
|
||||
|
||||
|
||||
class ErrorLogViewer(ttk.Frame):
|
||||
"""错误日志查看器组件"""
|
||||
|
||||
def __init__(self, parent: tk.Widget):
|
||||
super().__init__(parent)
|
||||
|
||||
# 创建界面组件
|
||||
self._create_widgets()
|
||||
self._setup_layout()
|
||||
|
||||
# 初始化数据
|
||||
self.error_entries: List[Dict[str, Any]] = []
|
||||
self.filtered_entries: List[Dict[str, Any]] = []
|
||||
|
||||
# 自动加载错误日志
|
||||
self._load_error_logs()
|
||||
|
||||
def _create_widgets(self) -> None:
|
||||
"""创建界面组件"""
|
||||
# 工具栏
|
||||
toolbar = ttk.Frame(self)
|
||||
toolbar.pack(fill="x", padx=5, pady=5)
|
||||
|
||||
# 刷新按钮
|
||||
self.refresh_btn = ttk.Button(toolbar, text="刷新", command=self._load_error_logs)
|
||||
self.refresh_btn.pack(side="left", padx=(0, 10))
|
||||
|
||||
# 时间范围选择
|
||||
ttk.Label(toolbar, text="时间范围:").pack(side="left", padx=(0, 5))
|
||||
self.time_range_var = tk.StringVar(value="全部")
|
||||
time_combo = ttk.Combobox(
|
||||
toolbar,
|
||||
textvariable=self.time_range_var,
|
||||
values=["全部", "今天", "最近24小时", "最近7天"],
|
||||
state="readonly",
|
||||
width=12
|
||||
)
|
||||
time_combo.pack(side="left", padx=(0, 10))
|
||||
time_combo.bind("<<ComboboxSelected>>", lambda e: self._filter_logs())
|
||||
|
||||
# 错误级别过滤
|
||||
ttk.Label(toolbar, text="错误级别:").pack(side="left", padx=(0, 5))
|
||||
self.level_var = tk.StringVar(value="全部")
|
||||
level_combo = ttk.Combobox(
|
||||
toolbar,
|
||||
textvariable=self.level_var,
|
||||
values=["全部", "CRITICAL", "ERROR", "WARNING", "INFO"],
|
||||
state="readonly",
|
||||
width=10
|
||||
)
|
||||
level_combo.pack(side="left", padx=(0, 10))
|
||||
level_combo.bind("<<ComboboxSelected>>", lambda e: self._filter_logs())
|
||||
|
||||
# 搜索框
|
||||
ttk.Label(toolbar, text="搜索:").pack(side="left", padx=(0, 5))
|
||||
self.search_var = tk.StringVar()
|
||||
search_entry = ttk.Entry(toolbar, textvariable=self.search_var, width=20)
|
||||
search_entry.pack(side="left", padx=(0, 5))
|
||||
search_entry.bind("<KeyRelease>", lambda e: self._filter_logs())
|
||||
|
||||
# 清除搜索按钮
|
||||
clear_btn = ttk.Button(toolbar, text="清除", command=self._clear_search)
|
||||
clear_btn.pack(side="left")
|
||||
|
||||
# 日志显示区域
|
||||
self.text_area = ScrolledText(self, wrap="word", font=("Consolas", 9))
|
||||
self.text_area.pack(fill="both", expand=True, padx=5, pady=(0, 5))
|
||||
|
||||
# 配置文本区域
|
||||
self.text_area.tag_configure("error", foreground="red")
|
||||
self.text_area.tag_configure("warning", foreground="orange")
|
||||
self.text_area.tag_configure("critical", foreground="darkred", font=("Consolas", 9, "bold"))
|
||||
self.text_area.tag_configure("timestamp", foreground="blue")
|
||||
self.text_area.tag_configure("module", foreground="green")
|
||||
|
||||
def _setup_layout(self) -> None:
|
||||
"""设置布局"""
|
||||
# 已在_create_widgets中完成
|
||||
|
||||
def _load_error_logs(self) -> None:
|
||||
"""加载错误日志"""
|
||||
try:
|
||||
self.error_entries.clear()
|
||||
|
||||
if not HAS_LOGGING:
|
||||
self._show_message("日志系统未初始化")
|
||||
return
|
||||
|
||||
error_log_path = get_error_log_path()
|
||||
|
||||
if not os.path.exists(error_log_path):
|
||||
self._show_message(f"错误日志文件不存在: {error_log_path}")
|
||||
return
|
||||
|
||||
# 读取错误日志文件
|
||||
with open(error_log_path, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
content = f.read()
|
||||
|
||||
# 解析日志条目(简单的行解析)
|
||||
lines = content.split('\n')
|
||||
current_entry: Optional[Dict[str, Any]] = None
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
# 检查是否是新的日志条目开始
|
||||
if self._is_log_entry_start(line):
|
||||
if current_entry:
|
||||
self.error_entries.append(current_entry)
|
||||
current_entry = self._parse_log_entry(line)
|
||||
elif current_entry is not None:
|
||||
# 添加到当前条目的详情
|
||||
current_entry['details'] = current_entry.get('details', '') + line + '\n'
|
||||
|
||||
# 添加最后一个条目
|
||||
if current_entry:
|
||||
self.error_entries.append(current_entry)
|
||||
|
||||
# 按时间倒序排序(最新的在前面)
|
||||
self.error_entries.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
|
||||
|
||||
# 应用过滤
|
||||
self._filter_logs()
|
||||
|
||||
except Exception as e:
|
||||
self._show_message(f"加载错误日志失败: {e}")
|
||||
|
||||
def _is_log_entry_start(self, line: str) -> bool:
|
||||
"""检查是否是日志条目的开始"""
|
||||
# 简单的检查:包含时间戳模式或错误关键词
|
||||
timestamp_pattern = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
|
||||
return (
|
||||
re.search(timestamp_pattern, line) is not None or
|
||||
any(keyword in line.upper() for keyword in ['ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION'])
|
||||
)
|
||||
|
||||
def _parse_log_entry(self, line: str) -> Dict[str, Any]:
|
||||
"""解析日志条目"""
|
||||
entry = {
|
||||
'raw_line': line,
|
||||
'level': 'UNKNOWN',
|
||||
'timestamp': '',
|
||||
'module': '',
|
||||
'message': line,
|
||||
'details': ''
|
||||
}
|
||||
|
||||
# 提取时间戳
|
||||
timestamp_match = re.search(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?)', line)
|
||||
if timestamp_match:
|
||||
entry['timestamp'] = timestamp_match.group(1)
|
||||
|
||||
# 提取错误级别
|
||||
for level in ['CRITICAL', 'ERROR', 'WARNING', 'INFO']:
|
||||
if level in line.upper():
|
||||
entry['level'] = level
|
||||
break
|
||||
|
||||
# 提取模块信息
|
||||
module_match = re.search(r'(\w+(?:\.\w+)*):', line)
|
||||
if module_match:
|
||||
entry['module'] = module_match.group(1)
|
||||
|
||||
return entry
|
||||
|
||||
def _filter_logs(self) -> None:
|
||||
"""应用过滤条件"""
|
||||
filtered = self.error_entries.copy()
|
||||
|
||||
# 时间范围过滤
|
||||
time_range = self.time_range_var.get()
|
||||
if time_range != "全部":
|
||||
cutoff_time = self._get_time_cutoff(time_range)
|
||||
filtered = [entry for entry in filtered
|
||||
if entry.get('timestamp') and
|
||||
self._parse_timestamp(entry['timestamp']) >= cutoff_time]
|
||||
|
||||
# 错误级别过滤
|
||||
level = self.level_var.get()
|
||||
if level != "全部":
|
||||
filtered = [entry for entry in filtered if entry.get('level') == level]
|
||||
|
||||
# 搜索过滤
|
||||
search_text = self.search_var.get().strip().lower()
|
||||
if search_text:
|
||||
filtered = [entry for entry in filtered
|
||||
if search_text in entry.get('raw_line', '').lower() or
|
||||
search_text in entry.get('details', '').lower()]
|
||||
|
||||
self.filtered_entries = filtered
|
||||
self._display_logs()
|
||||
|
||||
def _get_time_cutoff(self, time_range: str) -> datetime:
|
||||
"""获取时间截止点"""
|
||||
now = datetime.now()
|
||||
if time_range == "今天":
|
||||
return now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
elif time_range == "最近24小时":
|
||||
return now - timedelta(hours=24)
|
||||
elif time_range == "最近7天":
|
||||
return now - timedelta(days=7)
|
||||
else:
|
||||
return datetime.min
|
||||
|
||||
def _parse_timestamp(self, timestamp_str: str) -> datetime:
|
||||
"""解析时间戳字符串"""
|
||||
try:
|
||||
# 处理多种时间戳格式
|
||||
for fmt in ['%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M:%S']:
|
||||
try:
|
||||
return datetime.strptime(timestamp_str, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return datetime.min
|
||||
except Exception:
|
||||
return datetime.min
|
||||
|
||||
def _display_logs(self) -> None:
|
||||
"""显示过滤后的日志"""
|
||||
self.text_area.delete(1.0, "end")
|
||||
|
||||
if not self.filtered_entries:
|
||||
self.text_area.insert("end", "没有找到匹配的错误日志条目\n", "info")
|
||||
return
|
||||
|
||||
for entry in self.filtered_entries:
|
||||
self._display_log_entry(entry)
|
||||
self.text_area.insert("end", "\n" + "="*80 + "\n\n")
|
||||
|
||||
# 滚动到顶部
|
||||
self.text_area.see("1.0")
|
||||
|
||||
def _display_log_entry(self, entry: Dict[str, Any]) -> None:
|
||||
"""显示单个日志条目"""
|
||||
# 时间戳
|
||||
if entry.get('timestamp'):
|
||||
self.text_area.insert("end", f"[{entry['timestamp']}] ", "timestamp")
|
||||
|
||||
# 错误级别
|
||||
level = entry.get('level', 'UNKNOWN')
|
||||
self.text_area.insert("end", f"[{level}] ", level.lower())
|
||||
|
||||
# 模块
|
||||
if entry.get('module'):
|
||||
self.text_area.insert("end", f"[{entry['module']}] ", "module")
|
||||
|
||||
self.text_area.insert("end", "\n")
|
||||
|
||||
# 消息内容
|
||||
message = entry.get('raw_line', '')
|
||||
self.text_area.insert("end", message + "\n")
|
||||
|
||||
# 详情
|
||||
if entry.get('details'):
|
||||
self.text_area.insert("end", "\n详情:\n", "info")
|
||||
details = entry['details'].strip()
|
||||
if details:
|
||||
self.text_area.insert("end", details + "\n")
|
||||
|
||||
def _clear_search(self) -> None:
|
||||
"""清除搜索"""
|
||||
self.search_var.set("")
|
||||
self._filter_logs()
|
||||
|
||||
def _show_message(self, message: str) -> None:
|
||||
"""显示消息"""
|
||||
self.text_area.delete(1.0, "end")
|
||||
self.text_area.insert("end", message + "\n", "info")
|
||||
|
||||
|
||||
def create_error_log_view(parent: tk.Widget) -> ErrorLogViewer:
|
||||
"""创建错误日志查看器(兼容旧接口)"""
|
||||
return ErrorLogViewer(parent)
|
||||
@@ -47,3 +47,9 @@ def create_image_viewer(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+355
-15
@@ -1,13 +1,17 @@
|
||||
"""日志查看组件
|
||||
|
||||
包含日志显示、搜索等功能的GUI组件。
|
||||
包含日志显示、搜索、过滤、美化等功能的GUI组件。
|
||||
支持与新的模块化日志系统集成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Tuple, Callable
|
||||
from typing import Any, Callable, Optional, List, Dict
|
||||
import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
@@ -18,10 +22,351 @@ try:
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
|
||||
# 尝试导入日志模块
|
||||
try:
|
||||
from douyin.logging.log_formatter import (
|
||||
format_action_log, format_debug_log, format_error_log,
|
||||
beautify_log_output, colorize_log_line
|
||||
)
|
||||
from douyin.logging.performance_tracker import PerformanceTracker
|
||||
HAS_LOGGING_MODULES = True
|
||||
except ImportError:
|
||||
HAS_LOGGING_MODULES = False
|
||||
|
||||
# 尝试导入配置
|
||||
try:
|
||||
from config.config_manager import get_config_value
|
||||
HAS_CONFIG = True
|
||||
except ImportError:
|
||||
HAS_CONFIG = False
|
||||
|
||||
|
||||
class EnhancedLogViewer(ttk.Frame):
|
||||
"""增强的日志查看器组件"""
|
||||
|
||||
def __init__(self, parent: Any, log_queue: "queue.Queue[str]" = None):
|
||||
super().__init__(parent)
|
||||
|
||||
# 初始化数据
|
||||
self.log_queue = log_queue or queue.Queue()
|
||||
self.log_lines: List[str] = []
|
||||
self.filtered_lines: List[str] = []
|
||||
self.max_lines = self._get_config_value("logging.max_log_lines_display", 1000)
|
||||
self.auto_scroll = self._get_config_value("logging.auto_scroll_logs", True)
|
||||
self.beautify_output = self._get_config_value("logging.beautify_output", True)
|
||||
self.show_timestamps = self._get_config_value("logging.show_timestamps", True)
|
||||
self.color_output = self._get_config_value("logging.color_output", True)
|
||||
|
||||
# 创建界面
|
||||
self._create_widgets()
|
||||
self._setup_layout()
|
||||
|
||||
# 启动日志处理线程
|
||||
self.running = True
|
||||
self.log_thread = threading.Thread(target=self._process_logs, daemon=True)
|
||||
self.log_thread.start()
|
||||
|
||||
def _create_widgets(self) -> None:
|
||||
"""创建界面组件"""
|
||||
# 工具栏
|
||||
toolbar = ttk.Frame(self)
|
||||
toolbar.pack(fill="x", padx=5, pady=5)
|
||||
|
||||
# 过滤选项
|
||||
ttk.Label(toolbar, text="过滤:").pack(side="left", padx=(0, 5))
|
||||
|
||||
# 日志级别过滤
|
||||
self.level_var = tk.StringVar(value="全部")
|
||||
level_combo = ttk.Combobox(
|
||||
toolbar,
|
||||
textvariable=self.level_var,
|
||||
values=["全部", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
|
||||
state="readonly",
|
||||
width=8
|
||||
)
|
||||
level_combo.pack(side="left", padx=(0, 10))
|
||||
level_combo.bind("<<ComboboxSelected>>", lambda e: self._apply_filters())
|
||||
|
||||
# 时间范围过滤
|
||||
ttk.Label(toolbar, text="时间:").pack(side="left", padx=(0, 5))
|
||||
self.time_var = tk.StringVar(value="全部")
|
||||
time_combo = ttk.Combobox(
|
||||
toolbar,
|
||||
textvariable=self.time_var,
|
||||
values=["全部", "最近1小时", "最近24小时", "今天"],
|
||||
state="readonly",
|
||||
width=10
|
||||
)
|
||||
time_combo.pack(side="left", padx=(0, 10))
|
||||
time_combo.bind("<<ComboboxSelected>>", lambda e: self._apply_filters())
|
||||
|
||||
# 搜索框
|
||||
ttk.Label(toolbar, text="搜索:").pack(side="left", padx=(0, 5))
|
||||
self.search_var = tk.StringVar()
|
||||
search_entry = ttk.Entry(toolbar, textvariable=self.search_var, width=20)
|
||||
search_entry.pack(side="left", padx=(0, 5))
|
||||
search_entry.bind("<KeyRelease>", lambda e: self._apply_filters())
|
||||
|
||||
# 控制按钮
|
||||
ttk.Button(toolbar, text="清除", command=self._clear_logs).pack(side="right", padx=(5, 0))
|
||||
ttk.Button(toolbar, text="刷新", command=self._refresh_display).pack(side="right", padx=(5, 0))
|
||||
|
||||
# 美化开关
|
||||
self.beautify_var = tk.BooleanVar(value=self.beautify_output)
|
||||
ttk.Checkbutton(
|
||||
toolbar, text="美化显示", variable=self.beautify_var,
|
||||
command=self._toggle_beautify
|
||||
).pack(side="right", padx=(10, 0))
|
||||
|
||||
# 日志显示区域
|
||||
self.log_text = ScrolledText(self, wrap="word", font=("Consolas", 9))
|
||||
self.log_text.pack(fill="both", expand=True, padx=5, pady=(0, 5))
|
||||
|
||||
# 配置文本标签
|
||||
self._setup_text_tags()
|
||||
|
||||
def _setup_text_tags(self) -> None:
|
||||
"""设置文本标签样式"""
|
||||
if self.color_output:
|
||||
try:
|
||||
# 检查当前主题以应用合适的颜色方案
|
||||
is_light_theme = self._is_light_theme()
|
||||
|
||||
if is_light_theme:
|
||||
# 明亮主题颜色方案
|
||||
self.log_text.configure(background="#FFFFFF", foreground="#2C2C2C")
|
||||
self.log_text.tag_configure("timestamp", foreground="#8B8B8B") # 柔和灰色时间戳
|
||||
self.log_text.tag_configure("level_debug", foreground="#9E9E9E") # 浅灰色调试信息
|
||||
self.log_text.tag_configure("level_info", foreground="#1E88E5") # 明亮蓝色信息
|
||||
self.log_text.tag_configure("level_warning", foreground="#F57C00") # 橙色警告
|
||||
self.log_text.tag_configure("level_error", foreground="#D32F2F") # 深红色错误
|
||||
self.log_text.tag_configure("level_critical", foreground="#B71C1C", font=("Consolas", 9, "bold")) # 加粗深红色严重错误
|
||||
self.log_text.tag_configure("performance", foreground="#388E3C") # 深绿色性能
|
||||
self.log_text.tag_configure("module", foreground="#7B1FA2") # 紫色模块
|
||||
else:
|
||||
# 暗色主题颜色方案
|
||||
self.log_text.configure(background="#1E1E1E", foreground="#E0E0E0")
|
||||
self.log_text.tag_configure("timestamp", foreground="#A0A0A0") # 浅灰色时间戳
|
||||
self.log_text.tag_configure("level_debug", foreground="#B0B0B0") # 灰色调试信息
|
||||
self.log_text.tag_configure("level_info", foreground="#64B5F6") # 亮蓝色信息
|
||||
self.log_text.tag_configure("level_warning", foreground="#FFB74D") # 金色警告
|
||||
self.log_text.tag_configure("level_error", foreground="#EF5350") # 亮红色错误
|
||||
self.log_text.tag_configure("level_critical", foreground="#F44336", font=("Consolas", 9, "bold")) # 加粗亮红色严重错误
|
||||
self.log_text.tag_configure("performance", foreground="#81C784") # 亮绿色性能
|
||||
self.log_text.tag_configure("module", foreground="#BA68C8") # 亮紫色模块
|
||||
except Exception:
|
||||
pass # 忽略样式设置错误
|
||||
|
||||
def _is_light_theme(self) -> bool:
|
||||
"""检测是否为明亮主题"""
|
||||
try:
|
||||
# 尝试从配置中检测主题
|
||||
if HAS_CONFIG:
|
||||
theme = get_config_value("gui.theme", "litera")
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
return theme in light_themes
|
||||
except Exception:
|
||||
pass
|
||||
return True # 默认假设明亮主题
|
||||
|
||||
def _setup_layout(self) -> None:
|
||||
"""设置布局"""
|
||||
pass
|
||||
|
||||
def _get_config_value(self, key: str, default: Any) -> Any:
|
||||
"""获取配置值"""
|
||||
if HAS_CONFIG:
|
||||
try:
|
||||
return get_config_value(key, default)
|
||||
except Exception:
|
||||
pass
|
||||
return default
|
||||
|
||||
def _process_logs(self) -> None:
|
||||
"""处理日志队列"""
|
||||
while self.running:
|
||||
try:
|
||||
# 非阻塞获取日志
|
||||
while True:
|
||||
try:
|
||||
line = self.log_queue.get_nowait()
|
||||
self._add_log_line(line)
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print(f"日志处理错误: {e}")
|
||||
|
||||
time.sleep(0.1) # 避免CPU占用过高
|
||||
|
||||
def _add_log_line(self, line: str) -> None:
|
||||
"""添加日志行"""
|
||||
# 格式化日志行
|
||||
formatted_line = self._format_log_line(line)
|
||||
|
||||
# 添加到日志列表
|
||||
self.log_lines.append(formatted_line)
|
||||
|
||||
# 限制最大行数
|
||||
if len(self.log_lines) > self.max_lines:
|
||||
self.log_lines = self.log_lines[-self.max_lines:]
|
||||
|
||||
# 在UI线程中更新显示
|
||||
self.after(0, self._refresh_display)
|
||||
|
||||
def _format_log_line(self, line: str) -> str:
|
||||
"""格式化日志行"""
|
||||
if not self.beautify_output or not HAS_LOGGING_MODULES:
|
||||
return line
|
||||
|
||||
try:
|
||||
# 使用日志格式化模块美化输出
|
||||
return beautify_log_output(line)
|
||||
except Exception:
|
||||
return line
|
||||
|
||||
def _apply_filters(self) -> None:
|
||||
"""应用过滤条件"""
|
||||
level_filter = self.level_var.get()
|
||||
time_filter = self.time_var.get()
|
||||
search_filter = self.search_var.get().strip().lower()
|
||||
|
||||
filtered = []
|
||||
|
||||
for line in self.log_lines:
|
||||
# 级别过滤
|
||||
if level_filter != "全部":
|
||||
if not self._matches_level(line, level_filter):
|
||||
continue
|
||||
|
||||
# 时间过滤
|
||||
if time_filter != "全部":
|
||||
if not self._matches_time(line, time_filter):
|
||||
continue
|
||||
|
||||
# 搜索过滤
|
||||
if search_filter:
|
||||
if search_filter not in line.lower():
|
||||
continue
|
||||
|
||||
filtered.append(line)
|
||||
|
||||
self.filtered_lines = filtered
|
||||
self._refresh_display()
|
||||
|
||||
def _matches_level(self, line: str, level: str) -> bool:
|
||||
"""检查日志行是否匹配级别"""
|
||||
level_patterns = {
|
||||
"DEBUG": r'\bDEBUG\b',
|
||||
"INFO": r'\bINFO\b',
|
||||
"WARNING": r'\bWARNING\b',
|
||||
"ERROR": r'\bERROR\b',
|
||||
"CRITICAL": r'\bCRITICAL\b'
|
||||
}
|
||||
pattern = level_patterns.get(level)
|
||||
if pattern:
|
||||
return bool(re.search(pattern, line, re.IGNORECASE))
|
||||
return True
|
||||
|
||||
def _matches_time(self, line: str, time_filter: str) -> bool:
|
||||
"""检查日志行是否匹配时间范围"""
|
||||
# 提取时间戳
|
||||
timestamp_match = re.search(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})', line)
|
||||
if not timestamp_match:
|
||||
return True # 如果没有时间戳,默认匹配
|
||||
|
||||
try:
|
||||
log_time = datetime.strptime(timestamp_match.group(1), '%Y-%m-%d %H:%M:%S')
|
||||
now = datetime.now()
|
||||
|
||||
if time_filter == "今天":
|
||||
return log_time.date() == now.date()
|
||||
elif time_filter == "最近1小时":
|
||||
return log_time >= now - timedelta(hours=1)
|
||||
elif time_filter == "最近24小时":
|
||||
return log_time >= now - timedelta(hours=24)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
def _refresh_display(self) -> None:
|
||||
"""刷新显示"""
|
||||
try:
|
||||
# 清空文本
|
||||
self.log_text.delete(1.0, "end")
|
||||
|
||||
# 显示过滤后的日志
|
||||
lines_to_show = self.filtered_lines if self.filtered_lines else self.log_lines
|
||||
|
||||
for line in lines_to_show:
|
||||
self._insert_colored_line(line)
|
||||
self.log_text.insert("end", "\n")
|
||||
|
||||
# 自动滚动到底部
|
||||
if self.auto_scroll:
|
||||
self.log_text.see("end")
|
||||
|
||||
except Exception as e:
|
||||
print(f"刷新显示错误: {e}")
|
||||
|
||||
def _insert_colored_line(self, line: str) -> None:
|
||||
"""插入带颜色的日志行"""
|
||||
if not self.color_output:
|
||||
self.log_text.insert("end", line)
|
||||
return
|
||||
|
||||
try:
|
||||
# 为不同类型的日志应用颜色
|
||||
if "[DEBUG]" in line:
|
||||
self.log_text.insert("end", line, "level_debug")
|
||||
elif "[INFO]" in line:
|
||||
self.log_text.insert("end", line, "level_info")
|
||||
elif "[WARNING]" in line:
|
||||
self.log_text.insert("end", line, "level_warning")
|
||||
elif "[ERROR]" in line:
|
||||
self.log_text.insert("end", line, "level_error")
|
||||
elif "[CRITICAL]" in line:
|
||||
self.log_text.insert("end", line, "level_critical")
|
||||
elif "执行时间" in line or "耗时" in line:
|
||||
self.log_text.insert("end", line, "performance")
|
||||
elif re.search(r'\[[\w\.]+\]', line):
|
||||
self.log_text.insert("end", line, "module")
|
||||
else:
|
||||
self.log_text.insert("end", line)
|
||||
except Exception:
|
||||
# 如果颜色设置失败,回退到普通显示
|
||||
self.log_text.insert("end", line)
|
||||
|
||||
def _clear_logs(self) -> None:
|
||||
"""清除日志"""
|
||||
self.log_lines.clear()
|
||||
self.filtered_lines.clear()
|
||||
self.log_text.delete(1.0, "end")
|
||||
|
||||
def _toggle_beautify(self) -> None:
|
||||
"""切换美化显示"""
|
||||
self.beautify_output = self.beautify_var.get()
|
||||
# 重新格式化所有日志
|
||||
self.log_lines = [self._format_log_line(line) for line in self.log_lines]
|
||||
self._apply_filters()
|
||||
|
||||
def add_log_line(self, line: str) -> None:
|
||||
"""外部接口:添加日志行"""
|
||||
self._add_log_line(line)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止日志处理"""
|
||||
self.running = False
|
||||
|
||||
|
||||
def format_gui_log_line(line: str) -> str:
|
||||
"""将完整日志行转换为GUI显示用的精简版本。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
if HAS_LOGGING_MODULES:
|
||||
try:
|
||||
return beautify_log_output(line)
|
||||
except Exception:
|
||||
pass
|
||||
return line
|
||||
|
||||
|
||||
@@ -29,8 +374,8 @@ def create_log_viewer(
|
||||
parent: Any,
|
||||
log_queue: "queue.Queue[str]",
|
||||
on_line: Callable[[str], None]
|
||||
):
|
||||
"""创建日志查看器组件。
|
||||
) -> tuple[ScrolledText, Callable[[], None]]:
|
||||
"""创建日志查看器组件(兼容旧接口)。
|
||||
|
||||
参数:
|
||||
parent: 父容器
|
||||
@@ -40,18 +385,13 @@ def create_log_viewer(
|
||||
返回:
|
||||
(log_text, pump_logs_func) 日志文本框和日志泵函数
|
||||
"""
|
||||
log_text = ScrolledText(parent)
|
||||
log_text.pack(fill="both", expand=True, padx=10, pady=10)
|
||||
|
||||
try:
|
||||
log_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
# 创建增强的日志查看器
|
||||
viewer = EnhancedLogViewer(parent, log_queue)
|
||||
|
||||
def pump_logs():
|
||||
"""从队列中取出日志并显示。"""
|
||||
# TODO: 从原文件迁移函数实现
|
||||
"""从队列中取出日志并显示(兼容旧接口)。"""
|
||||
# 新的实现使用线程处理,不需要手动泵送
|
||||
pass
|
||||
|
||||
return log_text, pump_logs
|
||||
return viewer.log_text, pump_logs
|
||||
|
||||
@@ -43,3 +43,9 @@ def create_main_window(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -44,3 +44,9 @@ def create_ocr_panel(
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+377
-77
@@ -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", "暂无匹配的行为日志")
|
||||
|
||||
|
||||
+55
-18
@@ -808,16 +808,30 @@ class Runner:
|
||||
else:
|
||||
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
|
||||
|
||||
p = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=env,
|
||||
cwd=path_config.PROJECT_ROOT,
|
||||
)
|
||||
try:
|
||||
p = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=env,
|
||||
cwd=path_config.PROJECT_ROOT,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise RuntimeError(
|
||||
f"无法启动进程:找不到 Python 解释器或 run_cli.py 文件\n"
|
||||
f"Python路径: {sys.executable}\n"
|
||||
f"run_cli.py路径: {run_cli_path}\n"
|
||||
f"原始错误: {e}"
|
||||
)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"启动进程失败:{e}\n"
|
||||
f"命令: {' '.join(cmd)}\n"
|
||||
f"工作目录: {path_config.PROJECT_ROOT}"
|
||||
)
|
||||
|
||||
with self._lock:
|
||||
self._proc = p
|
||||
@@ -842,17 +856,40 @@ class Runner:
|
||||
out = self._proc.stdout
|
||||
if out is None:
|
||||
return
|
||||
for line in out:
|
||||
cleaned_line = line.rstrip("\n")
|
||||
self._on_line(cleaned_line)
|
||||
try:
|
||||
# 读取所有输出
|
||||
has_output = False
|
||||
for line in out:
|
||||
has_output = True
|
||||
cleaned_line = line.rstrip("\n")
|
||||
self._on_line(cleaned_line)
|
||||
try:
|
||||
self._update_stats_from_line(cleaned_line)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待进程结束
|
||||
rc = self._proc.wait()
|
||||
with self._lock:
|
||||
self._exit_code = rc
|
||||
|
||||
# 如果进程立即退出且没有输出,说明可能有问题
|
||||
if not has_output and rc != 0:
|
||||
self._on_line(f"[警告] 进程立即退出,退出码={rc},没有输出")
|
||||
self._on_line("[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误")
|
||||
else:
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
except Exception as e:
|
||||
# 读取输出时出错
|
||||
try:
|
||||
self._update_stats_from_line(cleaned_line)
|
||||
self._on_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}")
|
||||
except Exception:
|
||||
pass
|
||||
rc = self._proc.wait()
|
||||
with self._lock:
|
||||
self._exit_code = rc
|
||||
self._on_line(f"[进程结束] exit_code={rc}")
|
||||
|
||||
self._reader_thread = threading.Thread(target=_reader, daemon=True)
|
||||
self._reader_thread.start()
|
||||
|
||||
@@ -11,3 +11,9 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -19,3 +19,9 @@ __all__ = ["ProcRunner"]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user