Mongodb 慢查詢日志分析
使用 mloginfo
處理過的日志會在控制臺輸出, 顯示還是比較友好的.
但是如果內容較大, 就不方便查看了, 如果可以導入到 excel 就比較方便篩選/排序. 但是 mloginfo
并沒有提供生成到 excel 的功能. 可以通過一個 python 腳本輔助生成:
import pandas as pd
import re# 定義文件路徑
mloginfo_output_file = "mloginfo_output.txt" # 假設已經保存了 mloginfo 的輸出內容
excel_output_file = "mloginfo_slow_queries.xlsx"# 定義解析邏輯
def parse_mloginfo(file_path):parsed_data = []with open(file_path, "r", encoding="utf-8") as f:for line in f:# 跳過表頭或空行if line.startswith("namespace") or not line.strip():continue# 用正則表達式解析每一行match = re.match(r'^(?P<namespace>\S+)\s+(?P<operation>\S+)\s+(?P<pattern>\{.*?\}|None)\s+(?P<count>\d+)\s+(?P<min_ms>\d+)\s+(?P<max_ms>\d+)\s+(?P<percentile_95>\d+\.?\d*)\s+(?P<sum_ms>\d+)\s+(?P<mean_ms>\d+\.?\d*)\s+(?P<allowDiskUse>\S+)',line)if match:parsed_data.append(match.groupdict())return parsed_data# 調用解析邏輯
parsed_data = parse_mloginfo(mloginfo_output_file)# 如果有數據,轉換為 DataFrame 并保存為 Excel
if parsed_data:df = pd.DataFrame(parsed_data)# 轉換數據類型(如數字列)numeric_columns = ["count", "min_ms", "max_ms", "percentile_95", "sum_ms", "mean_ms"]for col in numeric_columns:df[col] = pd.to_numeric(df[col])# 保存為 Excel 文件df.to_excel(excel_output_file, index=False)print(f"慢查詢已成功保存到 {excel_output_file}")
else:print("未找到可解析的慢查詢數據。")
以下是一個更加完成的, 可以在命令參數中執行日志文件:
#!/usr/bin/env python
# -*- coding: utf-8 -*-import os
import re
import pandas as pd
import argparse# 設置命令行參數解析
parser = argparse.ArgumentParser(description="解析 mloginfo 輸出并保存為 Excel")
parser.add_argument("log_file", type=str, help="mloginfo 輸出文件路徑")
args = parser.parse_args()# Step 1: 運行 mloginfo 命令,捕獲輸出
log_file = args.log_fileoutput_file = f"{log_file}.txt"excel_output_file = f"{log_file}.xlsx"os.system(f"mloginfo {log_file} --queries > {output_file}")# 定義解析邏輯
def parse_mloginfo(file_path):parsed_data = []with open(file_path, "r", encoding="utf-8") as f:for line in f:# 跳過表頭或空行if line.startswith("namespace") or not line.strip():continue# 用正則表達式解析每一行match = re.match(r'^(?P<namespace>\S+)\s+(?P<operation>\S+)\s+(?P<pattern>\{.*?\}|None)\s+(?P<count>\d+)\s+(?P<min_ms>\d+)\s+(?P<max_ms>\d+)\s+(?P<percentile_95>\d+\.?\d*)\s+(?P<sum_ms>\d+)\s+(?P<mean_ms>\d+\.?\d*)\s+(?P<allowDiskUse>\S+)',line)if match:parsed_data.append(match.groupdict())return parsed_data# 調用解析邏輯
parsed_data = parse_mloginfo(output_file)# 如果有數據,轉換為 DataFrame 并保存為 Excel
if parsed_data:df = pd.DataFrame(parsed_data)# 轉換數據類型(如數字列)numeric_columns = ["count", "min_ms", "max_ms", "percentile_95", "sum_ms", "mean_ms"]for col in numeric_columns:df[col] = pd.to_numeric(df[col])# 調整列順序,將 pattern 列移到最后columns = [col for col in df.columns if col != "pattern"] + ["pattern"]df = df[columns]# 保存為 Excel 文件df.to_excel(excel_output_file, index=False)print(f"慢查詢已成功保存到 {excel_output_file}")
else:print("未找到可解析的慢查詢數據。")