Files
douyi_guaji_main/test_gui_logging_realtime.py
T
Your Name e68f1dd3de feat: Refactor coverage management and enhance logging functionality
- Removed the `.coverage` file from the repository to streamline coverage management.
- Updated `.gitignore` to exclude coverage-related files and directories, ensuring a cleaner project structure.
- Introduced new scripts for checking GPU availability and detecting GUI parameter conflicts, enhancing the overall functionality of the application.
- Improved logging mechanisms across various modules to support better debugging and monitoring.
- Added comprehensive documentation for new features and updated existing markdown files for clarity.
2025-12-23 02:38:51 +08:00

184 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
GUI日志实时测试脚本
通过运行run_cli.py来测试日志写入功能
"""
import os
import sys
import time
import subprocess
from datetime import datetime
# 确保在项目根目录
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from path_config import get_logs_dir, PROJECT_ROOT
def get_log_file_path():
"""获取今天的日志文件路径"""
log_dir = get_logs_dir()
today = datetime.now().strftime("%Y-%m-%d")
# 读取配置
try:
import json
config_path = os.path.join(PROJECT_ROOT, "config.json")
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
log_path = config.get("log_unified_path") or "logs/unified.log"
if not os.path.isabs(log_path):
log_path = os.path.join(PROJECT_ROOT, log_path)
use_dated_logs = config.get("logging", {}).get("use_dated_logs", True)
if use_dated_logs:
base_name = os.path.splitext(log_path)[0]
return f"{base_name}_{today}.log"
return log_path
except Exception:
pass
# 默认路径
return os.path.join(log_dir, f"unified_{today}.log")
def check_log_file(log_file_path: str, duration: int = 30):
"""检查日志文件在指定时间内的写入情况"""
print("=" * 60)
print("GUI日志实时测试")
print("=" * 60)
print(f"日志文件路径: {log_file_path}")
print(f"测试时长: {duration} 秒")
print()
# 检查日志文件是否存在
if not os.path.exists(log_file_path):
print(f"[警告] 日志文件不存在: {log_file_path}")
print("[信息] 等待日志文件创建...")
wait_time = 0
while not os.path.exists(log_file_path) and wait_time < 10:
time.sleep(1)
wait_time += 1
if not os.path.exists(log_file_path):
print("[错误] 日志文件未创建,测试失败")
return False
# 记录初始状态
initial_size = os.path.getsize(log_file_path)
print(f"[初始] 日志文件大小: {initial_size} bytes")
# 读取初始行数
with open(log_file_path, "r", encoding="utf-8-sig") as f:
initial_lines = len(f.readlines())
print(f"[初始] 日志文件行数: {initial_lines}")
# 记录最后几行
with open(log_file_path, "r", encoding="utf-8-sig") as f:
lines = f.readlines()
if lines:
print("\n[初始] 最后3行日志:")
for line in lines[-3:]:
print(f" {line.rstrip()}")
print(f"\n[测试] 开始监控日志文件 {duration} 秒...")
print("[测试] 请确保GUI应用正在运行并执行核心功能")
# 监控日志文件变化
check_interval = 5 # 每5秒检查一次
checks = duration // check_interval
last_size = initial_size
last_line_count = initial_lines
for i in range(checks):
time.sleep(check_interval)
if not os.path.exists(log_file_path):
print(f"[错误] 日志文件在检查 {i+1} 时消失")
return False
current_size = os.path.getsize(log_file_path)
with open(log_file_path, "r", encoding="utf-8-sig") as f:
current_lines = len(f.readlines())
size_diff = current_size - last_size
line_diff = current_lines - last_line_count
elapsed = (i + 1) * check_interval
print(f"[{elapsed:3d}s] 大小: {current_size:6d} bytes (+{size_diff:5d}) | "
f"行数: {current_lines:4d} (+{line_diff:3d})")
last_size = current_size
last_line_count = current_lines
# 最终检查
print("\n" + "=" * 60)
print("测试结果")
print("=" * 60)
final_size = os.path.getsize(log_file_path)
with open(log_file_path, "r", encoding="utf-8-sig") as f:
final_lines = len(f.readlines())
total_size_diff = final_size - initial_size
total_line_diff = final_lines - initial_lines
print(f"初始大小: {initial_size} bytes")
print(f"最终大小: {final_size} bytes")
print(f"增加大小: {total_size_diff} bytes")
print(f"初始行数: {initial_lines}")
print(f"最终行数: {final_lines}")
print(f"增加行数: {total_line_diff}")
# 检查日志格式
print("\n[验证] 检查日志格式...")
with open(log_file_path, "r", encoding="utf-8-sig") as f:
lines = f.readlines()
format_ok = True
timestamp_ok = True
# 检查最后10行的格式
check_lines = lines[-10:] if len(lines) >= 10 else lines
for line in check_lines:
line = line.strip()
if not line:
continue
# 检查时间戳格式
if not (line[0].isdigit() and " - [" in line):
# 如果没有时间戳,检查是否是GUI添加的
if "[GUI] -" not in line:
format_ok = False
print(f" [警告] 格式异常: {line[:80]}")
# 检查时间戳格式(YYYY-MM-DD HH:MM:SS)
if line[0].isdigit():
try:
date_part = line.split(" - ")[0]
datetime.strptime(date_part[:19], "%Y-%m-%d %H:%M:%S")
except Exception:
timestamp_ok = False
print(f" [警告] 时间戳格式异常: {line[:80]}")
print(f"\n[结果] 日志文件写入: {'正常' if total_line_diff > 0 else '异常'}")
print(f"[结果] 日志格式检查: {'通过' if format_ok else '失败'}")
print(f"[结果] 时间戳格式检查: {'通过' if timestamp_ok else '失败'}")
# 显示最后5行
print("\n[最终] 最后5行日志:")
for line in lines[-5:]:
print(f" {line.rstrip()}")
# 判断测试是否通过
if total_line_diff > 0 and format_ok and timestamp_ok:
print("\n[总结] 测试通过!日志写入功能正常。")
return True
else:
print("\n[总结] 测试失败,请检查日志写入功能。")
return False
if __name__ == "__main__":
log_file = get_log_file_path()
success = check_log_file(log_file, duration=30)
sys.exit(0 if success else 1)