Refactor detailed_time_analysis.py for improved readability and add log_filter.py for keyword-based log filtering
- Cleaned up code formatting and improved readability in detailed_time_analysis.py. - Introduced a new script, log_filter.py, to filter log files based on user-defined keywords, with options for outputting results to a file.
This commit is contained in:
1 parent
735a04722d
commit
d1f1c8f682
4 files changed
+740
-57
No files matched your search
@@ -15,32 +15,48 @@ from datetime import datetime
|
||||
# Ensure UTF-8 output on Windows
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
if hasattr(sys.stdout, 'reconfigure'):
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def parse_logs(log_paths):
|
||||
data = defaultdict(list)
|
||||
|
||||
|
||||
# 更通用的正则,适应 actions.log 和 unified log
|
||||
# 匹配: [GUI] - Tag [OP] Msg ... 耗时:Val
|
||||
gui_op_re = re.compile(r'\[GUI\]\s*-\s*(.*?)\s*\[OP\]\s*(.*?)\s*(?:elapsed_seconds|elapsed_ms|耗时[:=])\s*=?\s*([\d.]+)([ms]?)', re.I)
|
||||
|
||||
# 匹配: [Tag] Msg ... 耗时:Val (非 [GUI] 开头的格式)
|
||||
tag_op_re = re.compile(r'\[([^\]\d]{2,15})\]\s*(.*?)\s*(?:elapsed_seconds|elapsed_ms|耗时[:=])\s*=?\s*([\d.]+)([ms]?)', re.I)
|
||||
gui_op_re = re.compile(
|
||||
r"\[GUI\]\s*-\s*(.*?)\s*\[OP\]\s*(.*?)\s*(?:elapsed_seconds|elapsed_ms|耗时[:=])\s*=?\s*([\d.]+)([ms]?)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
exclude_tags = {'INFO', 'DEBUG', 'ERROR', 'WARN', 'WARNING', 'TRACE', 'GUI', 'ACTIONLOGGER'}
|
||||
# 匹配: [Tag] Msg ... 耗时:Val (非 [GUI] 开头的格式)
|
||||
tag_op_re = re.compile(
|
||||
r"\[([^\]\d]{2,15})\]\s*(.*?)\s*(?:elapsed_seconds|elapsed_ms|耗时[:=])\s*=?\s*([\d.]+)([ms]?)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
exclude_tags = {
|
||||
"INFO",
|
||||
"DEBUG",
|
||||
"ERROR",
|
||||
"WARN",
|
||||
"WARNING",
|
||||
"TRACE",
|
||||
"GUI",
|
||||
"ACTIONLOGGER",
|
||||
}
|
||||
|
||||
for log_path in log_paths:
|
||||
if not os.path.exists(log_path):
|
||||
continue
|
||||
|
||||
|
||||
print(f"Reading {log_path}...")
|
||||
with open(log_path, 'r', encoding='utf-8', errors='replace') as f:
|
||||
with open(log_path, "r", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
tag, msg, val_str, unit = None, None, None, None
|
||||
|
||||
|
||||
# 尝试匹配 [GUI] - Tag [OP] 格式
|
||||
m = gui_op_re.search(line)
|
||||
if m:
|
||||
@@ -50,86 +66,101 @@ def parse_logs(log_paths):
|
||||
m = tag_op_re.search(line)
|
||||
if m:
|
||||
tag, msg, val_str, unit = m.groups()
|
||||
|
||||
|
||||
if tag and msg:
|
||||
if tag.upper() in exclude_tags:
|
||||
continue
|
||||
|
||||
|
||||
val = float(val_str)
|
||||
is_ms = False
|
||||
if unit.lower() in ['ms', 'm']:
|
||||
if unit.lower() in ["ms", "m"]:
|
||||
is_ms = True
|
||||
elif '耗时=' in line and val > 5: # The bug
|
||||
elif "耗时=" in line and val > 5: # The bug
|
||||
is_ms = True
|
||||
|
||||
|
||||
value = val if is_ms else val * 1000
|
||||
|
||||
|
||||
# 清理 Msg
|
||||
# 避免使用 '.' 在正则中未转义的情况
|
||||
clean_msg = msg
|
||||
# 1. 移除 (等待开奖中) 这种括号内容
|
||||
clean_msg = re.sub(r'(.*?等待开奖.*?)', '', clean_msg)
|
||||
clean_msg = re.sub(r'\(.*?等待开奖.*?\)', '', clean_msg)
|
||||
|
||||
clean_msg = re.sub(r"(.*?等待开奖.*?)", "", clean_msg)
|
||||
clean_msg = re.sub(r"\(.*?等待开奖.*?\)", "", clean_msg)
|
||||
|
||||
# 2. 按照特定关键词拆分,取前面的部分作为操作名
|
||||
split_keywords = ['完成', 'elapsed', '耗时', '成功', '失败', '开始', '结束', '...', '---', '步骤']
|
||||
split_keywords = [
|
||||
"完成",
|
||||
"elapsed",
|
||||
"耗时",
|
||||
"成功",
|
||||
"失败",
|
||||
"开始",
|
||||
"结束",
|
||||
"...",
|
||||
"---",
|
||||
"步骤",
|
||||
]
|
||||
for kw in split_keywords:
|
||||
if kw in clean_msg:
|
||||
clean_msg = clean_msg.split(kw)[0]
|
||||
|
||||
|
||||
# 3. 统一特殊长内容
|
||||
if '完整识别结果' in clean_msg:
|
||||
clean_msg = '完整识别结果'
|
||||
if '等待开奖中' in clean_msg:
|
||||
clean_msg = '等待开奖中'
|
||||
if '未检测到福袋图标' in clean_msg:
|
||||
clean_msg = '未检测到福袋图标'
|
||||
if '检测到福袋图标' in clean_msg:
|
||||
clean_msg = '检测到福袋图标'
|
||||
|
||||
if "完整识别结果" in clean_msg:
|
||||
clean_msg = "完整识别结果"
|
||||
if "等待开奖中" in clean_msg:
|
||||
clean_msg = "等待开奖中"
|
||||
if "未检测到福袋图标" in clean_msg:
|
||||
clean_msg = "未检测到福袋图标"
|
||||
if "检测到福袋图标" in clean_msg:
|
||||
clean_msg = "检测到福袋图标"
|
||||
|
||||
# 4. 移除括号
|
||||
clean_msg = re.sub(r'(.*?)', '', clean_msg)
|
||||
clean_msg = re.sub(r'\(.*?\)', '', clean_msg)
|
||||
|
||||
clean_msg = clean_msg.strip(' ,,|:-_')
|
||||
|
||||
clean_msg = re.sub(r"(.*?)", "", clean_msg)
|
||||
clean_msg = re.sub(r"\(.*?\)", "", clean_msg)
|
||||
|
||||
clean_msg = clean_msg.strip(" ,,|:-_")
|
||||
|
||||
if not clean_msg:
|
||||
continue
|
||||
|
||||
|
||||
category = f"[{tag}] {clean_msg}"
|
||||
data[category].append(value)
|
||||
continue
|
||||
|
||||
# 特殊格式处理 (截图)
|
||||
m = re.search(r'\[截图\].*?总耗时\(ms\)=([\d.]+)', line)
|
||||
m = re.search(r"\[截图\].*?总耗时\(ms\)=([\d.]+)", line)
|
||||
if m:
|
||||
data["[截图] 获取屏幕截图"].append(float(m.group(1)))
|
||||
continue
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def analyze(data):
|
||||
results = []
|
||||
for category, values in data.items():
|
||||
if not values:
|
||||
continue
|
||||
arr = np.array(values)
|
||||
results.append({
|
||||
'category': category,
|
||||
'count': len(arr),
|
||||
'avg': np.mean(arr),
|
||||
'p50': np.percentile(arr, 50),
|
||||
'p80': np.percentile(arr, 80),
|
||||
'p95': np.percentile(arr, 95),
|
||||
'min': np.min(arr),
|
||||
'max': np.max(arr),
|
||||
'total': np.sum(arr)
|
||||
})
|
||||
|
||||
results.append(
|
||||
{
|
||||
"category": category,
|
||||
"count": len(arr),
|
||||
"avg": np.mean(arr),
|
||||
"p50": np.percentile(arr, 50),
|
||||
"p80": np.percentile(arr, 80),
|
||||
"p95": np.percentile(arr, 95),
|
||||
"min": np.min(arr),
|
||||
"max": np.max(arr),
|
||||
"total": np.sum(arr),
|
||||
}
|
||||
)
|
||||
|
||||
# Sort by average duration descending
|
||||
results.sort(key=lambda x: x['avg'], reverse=True)
|
||||
results.sort(key=lambda x: x["avg"], reverse=True)
|
||||
return results
|
||||
|
||||
|
||||
def print_table(results):
|
||||
header = f"{'Operation':<55} | {'Count':>6} | {'Avg':>8} | {'P50':>8} | {'P80':>8} | {'P95':>8} | {'Max':>8}"
|
||||
sep = "-" * len(header)
|
||||
@@ -137,24 +168,27 @@ def print_table(results):
|
||||
print(header)
|
||||
print(sep)
|
||||
for r in results:
|
||||
print(f"{r['category'][:55]:<55} | {r['count']:>6} | {r['avg']:>8.1f} | {r['p50']:>8.1f} | {r['p80']:>8.1f} | {r['p95']:>8.1f} | {r['max']:>8.1f}")
|
||||
print(
|
||||
f"{r['category'][:55]:<55} | {r['count']:>6} | {r['avg']:>8.1f} | {r['p50']:>8.1f} | {r['p80']:>8.1f} | {r['p95']:>8.1f} | {r['max']:>8.1f}"
|
||||
)
|
||||
print(sep)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logs_dir = "logs"
|
||||
latest_unified = None
|
||||
all_logs = []
|
||||
|
||||
|
||||
# Get all logs from last 3 days or so
|
||||
if os.path.exists(logs_dir):
|
||||
files = os.listdir(logs_dir)
|
||||
# Sort files to find the latest
|
||||
files.sort(reverse=True)
|
||||
|
||||
|
||||
# Add actions.log
|
||||
if "actions.log" in files:
|
||||
all_logs.append(os.path.join(logs_dir, "actions.log"))
|
||||
|
||||
|
||||
# Add a few recent unified logs
|
||||
unified_count = 0
|
||||
for f in files:
|
||||
@@ -163,11 +197,11 @@ if __name__ == "__main__":
|
||||
unified_count += 1
|
||||
if unified_count >= 3:
|
||||
break
|
||||
|
||||
|
||||
if not all_logs:
|
||||
print("No logs found.")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
data = parse_logs(all_logs)
|
||||
results = analyze(data)
|
||||
print_table(results)
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
日志关键字筛选工具
|
||||
用法: python log_filter.py <日志文件路径> <关键字> [输出文件]
|
||||
示例: python log_filter.py logs/actions.log "参与成功"
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def filter_log_by_keyword(log_file_path, keyword, output_file=None):
|
||||
"""
|
||||
根据关键字筛选日志文件
|
||||
"""
|
||||
if not os.path.exists(log_file_path):
|
||||
print("错误: 日志文件不存在: {}".format(log_file_path))
|
||||
return
|
||||
|
||||
try:
|
||||
pattern = re.compile(keyword, re.IGNORECASE)
|
||||
except re.error as e:
|
||||
print("错误: 无效的正则表达式 '{}': {}".format(keyword, e))
|
||||
return
|
||||
|
||||
matched_lines = []
|
||||
total_lines = 0
|
||||
|
||||
print("正在筛选日志文件: {}".format(log_file_path))
|
||||
print("关键字: {}".format(keyword))
|
||||
|
||||
try:
|
||||
with open(log_file_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
for line_num, line in enumerate(f, 1):
|
||||
total_lines = line_num
|
||||
if pattern.search(line):
|
||||
matched_lines.append("行{}: {}".format(line_num, line.rstrip()))
|
||||
|
||||
print("总行数: {}".format(total_lines))
|
||||
print("匹配行数: {}".format(len(matched_lines)))
|
||||
|
||||
if output_file:
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
f.write("日志筛选结果\n")
|
||||
f.write("文件: {}\n".format(log_file_path))
|
||||
f.write("关键字: {}\n".format(keyword))
|
||||
f.write("总行数: {}\n".format(total_lines))
|
||||
f.write("匹配行数: {}\n".format(len(matched_lines)))
|
||||
f.write("=" * 50 + "\n\n")
|
||||
for line in matched_lines:
|
||||
f.write(line + "\n")
|
||||
print("结果已保存到: {}".format(output_file))
|
||||
else:
|
||||
print("\n匹配的行:")
|
||||
print("=" * 50)
|
||||
for line in matched_lines[:50]:
|
||||
print(line)
|
||||
if len(matched_lines) > 50:
|
||||
print(
|
||||
"\n... 还有 {} 行匹配 (使用输出文件参数查看全部)".format(
|
||||
len(matched_lines) - 50
|
||||
)
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print("错误: 处理文件时出错: {}".format(e))
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print("用法: python log_filter.py <日志文件路径> <关键字> [输出文件]")
|
||||
print("示例:")
|
||||
print(' python log_filter.py logs/actions.log "参与成功"')
|
||||
print(' python log_filter.py logs/unified_20260112.log "流程" result.txt')
|
||||
print(' python log_filter.py logs/actions.log "elapsed_seconds" timing.txt')
|
||||
sys.exit(1)
|
||||
|
||||
log_file = sys.argv[1]
|
||||
keyword = sys.argv[2]
|
||||
output_file = sys.argv[3] if len(sys.argv) > 3 else None
|
||||
|
||||
if not os.path.isabs(log_file):
|
||||
project_root = Path(__file__).parent.parent
|
||||
log_file = str(project_root / log_file)
|
||||
|
||||
filter_log_by_keyword(log_file, keyword, output_file)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user