Files
douyi_guaji_main/tools/analyze_screenshot_logs.py
T
2025-12-31 11:55:01 +08:00

137 lines
4.4 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""分析日志中的截图耗时,评估优化效果"""
import sys
import os
import re
from datetime import datetime
# 设置UTF-8输出
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
def analyze_log_file(log_path):
"""分析日志文件"""
if not os.path.exists(log_path):
print(f"日志文件不存在: {log_path}")
return
print("=" * 60)
print("截图性能分析")
print("=" * 60)
print()
# 读取日志文件
try:
with open(log_path, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print(f"读取日志文件失败: {e}")
return
# 查找截图相关的日志
screenshot_times = []
service_started = False
for line in lines:
# 检查服务启动
if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line:
service_started = True
print(f"✅ 发现服务启动日志: {line.strip()[:100]}")
# 查找截图耗时
if 'screenshot_elapsed_seconds' in line:
# 提取耗时
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
screenshot_times.append(elapsed)
# 查找截图成功日志
if '[截图]' in line and '成功' in line:
# 尝试提取时间戳
timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if timestamp_match:
pass # 可以用于分析时间间隔
# 分析结果
print(f"\n服务启动状态: {'✅ 已启动' if service_started else '❌ 未启动'}")
print()
if screenshot_times:
print(f"截图耗时统计(共 {len(screenshot_times)} 次):")
print(f" 平均耗时: {sum(screenshot_times) / len(screenshot_times):.2f} 秒")
print(f" 最短耗时: {min(screenshot_times):.2f} 秒")
print(f" 最长耗时: {max(screenshot_times):.2f} 秒")
print()
# 分析优化效果
avg_time = sum(screenshot_times) / len(screenshot_times)
if service_started:
if avg_time < 0.5:
print("✅✅✅ 优化效果显著!平均耗时 < 0.5秒")
elif avg_time < 1.0:
print("✅✅ 优化效果良好!平均耗时 < 1秒")
elif avg_time < 2.0:
print("✅ 优化效果一般,平均耗时 < 2秒")
else:
print("⚠️ 优化效果不明显,平均耗时 >= 2秒")
else:
print("⚠️ 服务未启动,这是优化前的性能")
print(" 预期优化后: 缓存命中 < 0.01秒,缓存未命中 0.5-1秒")
else:
print("未找到截图耗时数据")
# 查找最近的截图日志
print()
print("最近的截图日志(最后5条):")
screenshot_logs = [line for line in lines if '[截图]' in line and '成功' in line]
for log in screenshot_logs[-5:]:
print(f" {log.strip()[:150]}")
def main():
"""主函数"""
# 查找最新的日志文件
log_dir = "logs"
if not os.path.exists(log_dir):
print(f"日志目录不存在: {log_dir}")
return
# 查找最新的 unified_*.log 文件
log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')]
if not log_files:
print("未找到 unified_*.log 文件")
return
# 按修改时间排序
log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True)
latest_log = os.path.join(log_dir, log_files[0])
print(f"分析日志文件: {latest_log}")
print()
analyze_log_file(latest_log)
print()
print("=" * 60)
print("分析完成")
print("=" * 60)
# 建议
print()
print("建议:")
print("1. 如果服务未启动,请重新运行程序(代码已更新)")
print("2. 如果服务已启动但性能未提升,检查缓存是否生效")
print("3. 查看日志中是否有服务启动的错误信息")
if __name__ == '__main__':
main()