编写高效的日志分析脚本可以帮助你快速定位问题、监控系统性能以及优化应用程序。以下是一些关键步骤和最佳实践,用于编写高效的日志分析脚本:
logging模块、pandas、numpy、re(正则表达式)等。import re
from collections import defaultdict
# 定义日志格式
log_pattern = re.compile(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\w+) (\w+) (.*)')
# 初始化数据结构
log_data = defaultdict(list)
def parse_log_line(line):
match = log_pattern.match(line)
if match:
timestamp, level, thread, message = match.groups()
log_data[level].append((timestamp, thread, message))
# 读取日志文件并解析
with open('app.log', 'r') as file:
for line in file:
parse_log_line(line)
# 分析日志数据
for level, entries in log_data.items():
print(f"Level {level}:")
for entry in entries:
print(f" {entry}")
import pandas as pd
# 将解析后的日志数据转换为DataFrame
df = pd.DataFrame(log_data['ERROR'], columns=['timestamp', 'thread', 'message'])
# 统计错误次数
error_count = df.shape[0]
print(f"Total errors: {error_count}")
# 按时间排序并显示前10条错误日志
top_errors = df.sort_values(by='timestamp').head(10)
print(top_errors)
通过以上步骤,你可以编写出高效且功能强大的日志分析脚本。不断优化和扩展脚本,以满足不断变化的需求。