Files
douyi_guaji_main/gui/components/log_viewer.py
T
CodexandClaude Opus 4.7 96f8600d42 小批量收尾:删除零引用 scrcpy_screenshot + douyin_fudai/log_viewer print→logger
- 删除 operations/scrcpy_screenshot.py(100 行,仅自身定义自身使用,全仓零外部引用)
- douyin/core/douyin_fudai.py:3 处兜底 print → logging.info/warning(_log_kv 失败时的兜底路径)
- gui/components/log_viewer.py:2 处错误 print → _LOGVIEW_LOGGER.exception(日志线程异常 / 刷新显示异常)

回归:149→148 .py,全量编译通过;test_filter_logging / check_web_gui_config_sync 通过;
fudai_analyse 类正常导出,log_viewer 模块加载 OK。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:40:18 +08:00

436 lines
16 KiB
Python

"""日志查看组件
包含日志显示、搜索、过滤、美化等功能的GUI组件。
支持与新的模块化日志系统集成。
"""
from __future__ import annotations
from typing import Any, Callable, Optional, List, Dict, Tuple
import logging
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
# 模块级 logger:内部错误(日志线程异常 / 刷新显示异常)走 logging,避免裸 print
_LOGVIEW_LOGGER = logging.getLogger("gui.components.log_viewer")
try:
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
ScrolledText = TBSrolledText
except ImportError:
from tkinter.scrolledtext import ScrolledText
# 尝试导入日志模块
try:
from douyin.logging.log_formatter import ( # type: ignore[assignment]
format_action_log,
format_debug_log,
format_error_log,
beautify_log_output,
colorize_log_line
)
from douyin.logging.performance_tracker import PerformanceTracker # type: ignore[assignment]
HAS_LOGGING_MODULES = True
except ImportError:
# 如果导入失败,提供占位符函数(带显式类型注解以避免 Literal[''] 推断)
def format_action_log(*args, **kwargs) -> str:
return ""
def format_debug_log(*args, **kwargs) -> str:
return ""
def format_error_log(*args, **kwargs) -> str:
return ""
def beautify_log_output(line: str) -> str:
return line
def colorize_log_line(*args, **kwargs) -> str:
return ""
class PerformanceTracker:
def __init__(self, *args, **kwargs): pass
def start_timer(self, *args, **kwargs): pass
def end_timer(self, *args, **kwargs): pass
def get_statistics(self, *args, **kwargs): return {}
HAS_LOGGING_MODULES = False
# 尝试导入配置
try:
from config.config_manager import get_config_value # type: ignore[assignment,import]
HAS_CONFIG = True
except ImportError:
# 如果导入失败,提供占位符函数
def get_config_value(key, default=None):
return default
HAS_CONFIG = False
# 为兼容静态类型检查,将实际导入或占位函数转换为 Any(避免赋值/导入时的类型不匹配报错)
from typing import Any as _Any, cast
format_action_log = cast(_Any, format_action_log)
format_debug_log = cast(_Any, format_debug_log)
format_error_log = cast(_Any, format_error_log)
beautify_log_output = cast(_Any, beautify_log_output)
colorize_log_line = cast(_Any, colorize_log_line)
PerformanceTracker = cast(_Any, PerformanceTracker)
class EnhancedLogViewer(ttk.Frame):
"""增强的日志查看器组件"""
def __init__(self, parent: Any, log_queue: Optional[queue.Queue] = 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:
_LOGVIEW_LOGGER.exception("日志处理错误: %s", 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:
_LOGVIEW_LOGGER.exception("刷新显示错误: %s", 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显示用的精简版本。"""
if HAS_LOGGING_MODULES:
try:
return beautify_log_output(line)
except Exception:
pass
return line
def create_log_viewer(
parent: Any,
log_queue: Optional[queue.Queue],
on_line: Callable[[str], None]
) -> Any:
"""创建日志查看器组件(兼容旧接口)。
参数:
parent: 父容器
log_queue: 日志队列
on_line: 日志输出回调
返回:
(log_text, pump_logs_func) 日志文本框和日志泵函数
"""
# 创建增强的日志查看器
viewer = EnhancedLogViewer(parent, log_queue)
def pump_logs():
"""从队列中取出日志并显示(兼容旧接口)。"""
# 新的实现使用线程处理,不需要手动泵送
pass
return viewer.log_text, pump_logs