Python Pandas 与 Jupyter Notebook 日志分析与可视化实战指南
在日常的系统运维和开发工作中,日志分析是一个不可或缺的环节。通过对日志的分析,我们可以快速定位系统问题、优化性能并预测潜在风险。本文将介绍如何使用 Python、Pandas 和 Jupyter Notebook 对杂乱的日志文件进行清洗、分析和可视化,统计高频错误类型并生成直观的图表。
实验目标
使用 Python、Pandas 和 Jupyter Notebook 等工具,对杂乱的日志文件进行以下操作:
-
导入杂乱日志文件(含冗余、错误格式)。
-
使用 Pandas 清洗日志(去重、时间格式化、提取关键字段)。
-
编写脚本统计高频错误类型并生成可视化图表(Matplotlib)。
实验步骤
1. 导入日志文件
首先,我们需要将杂乱的日志文件导入程序中,以便后续处理。这里我们使用 Python 的 open
函数读取日志文件,并将文件内容存储到一个列表中。
Python复制
log_file = 'error_logs.log' # 替换为你的日志文件路径
# 读取日志文件
with open(log_file, 'r', encoding='utf-8') as f:
logs = f.readlines()
# 查看前 10 行日志
print("原始日志示例:")
print(logs[:10])
2. 清洗日志数据
日志文件通常包含大量的冗余信息和不规范的格式,我们需要对这些数据进行清洗,提取关键字段并进行格式化。
2.1 提取关键字段
使用正则表达式提取日志中的关键字段,如 IP 地址、时间戳、请求方法、状态码和响应大小。
Python复制
import re
log_pattern = r'(\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(.*?)" (\d+) (\d+|-)'
parsed_logs = []
for log in logs:
match = re.match(log_pattern, log)
if match:
ip, timestamp, request, status, size = match.groups()
parsed_logs.append({
'ip': ip,
'timestamp': timestamp,
'request': request,
'status': status,
'size': size
})
2.2 转换为 DataFrame
将提取的数据转换为 Pandas 的 DataFrame,方便后续分析。
Python复制
import pandas as pd
df = pd.DataFrame(parsed_logs)
2.3 数据清洗
去除重复的记录,格式化时间戳,并处理缺失值。
Python复制
# 去重
df = df.drop_duplicates()
# 时间格式化
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
# 处理缺失值
df = df.dropna(subset=['timestamp'])
3. 统计高频错误类型
提取状态码为 4xx 或 5xx 的错误记录,并统计每种错误类型的出现次数。
Python复制
# 提取错误记录
error_logs = df[df['status'].astype(str).str.startswith('4') | df['status'].astype(str).str.startswith('5')]
# 统计错误类型
error_counts = error_logs['status'].value_counts().sort_index()
print("\n错误类型统计:")
print(error_counts)
4. 生成可视化图表
使用 Matplotlib 创建柱状图和饼图,直观展示错误类型的分布和比例。
Python复制
import matplotlib.pyplot as plt
import matplotlib
# 设置 Matplotlib 字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
matplotlib.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 创建图表
plt.figure(figsize=(12, 8))
# 柱状图:错误类型分布
plt.subplot(1, 2, 1)
error_counts.plot(kind='bar', color='skyblue')
plt.title('错误类型分布')
plt.xlabel('状态码')
plt.ylabel('出现次数')
plt.xticks(rotation=0)
# 饼图:错误类型比例
plt.subplot(1, 2, 2)
error_counts.plot(kind='pie', autopct='%1.1f%%', startangle=90)
plt.title('错误类型比例')
plt.ylabel('')
# 调整布局
plt.tight_layout()
# 保存图表
plt.savefig('error_analysis.png', dpi=300)
# 显示图表
plt.show()
完整代码如下
以下是完整的代码,可以直接在Jupyter Notebook中运行:
import pandas as pd
import re
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# 设置Matplotlib字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
matplotlib.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 导入日志文件
log_file = 'error_logs.log' # 替换为你的日志文件路径
# 读取日志文件
with open(log_file, 'r', encoding='utf-8') as f:
logs = f.readlines()
# 查看前10行日志
print("原始日志示例:")
print(logs[:10])
# 定义正则表达式,提取关键字段
log_pattern = r'(\d+\.\d+\.\d+\.\d+) - - \[(.*?)\] "(.*?)" (\d+) (\d+|-)'
# 解析日志
parsed_logs = []
for log in logs:
match = re.match(log_pattern, log)
if match:
ip, timestamp, request, status, size = match.groups()
parsed_logs.append({
'ip': ip,
'timestamp': timestamp,
'request': request,
'status': status,
'size': size
})
# 转换为DataFrame
df = pd.DataFrame(parsed_logs)
# 查看清洗后的数据
print("\n清洗后的数据示例:")
print(df.head())
# 去重
df = df.drop_duplicates()
# 时间格式化
df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')
# 处理缺失值
df = df.dropna(subset=['timestamp'])
# 查看清洗后的数据
print("\n清洗后的数据统计:")
print(f"总记录数: {len(df)}")
print(df.info())
# 提取状态码并统计错误类型
error_logs = df[df['status'].astype(str).str.startswith('4') | df['status'].astype(str).str.startswith('5')]
error_counts = error_logs['status'].value_counts().sort_index()
print("\n错误类型统计:")
print(error_counts)
# 创建图表
plt.figure(figsize=(12, 8))
# 柱状图:错误类型分布
plt.subplot(1, 2, 1)
error_counts.plot(kind='bar', color='skyblue')
plt.title('错误类型分布')
plt.xlabel('状态码')
plt.ylabel('出现次数')
plt.xticks(rotation=0)
# 饼图:错误类型比例
plt.subplot(1, 2, 2)
error_counts.plot(kind='pie', autopct='%1.1f%%', startangle=90)
plt.title('错误类型比例')
plt.ylabel('')
# 调整布局
plt.tight_layout()
# 保存图表
plt.savefig('error_analysis.png', dpi=300)
# 显示图表
plt.show()
注意:
程序无法找到名为 error_logs.log
的文件。这通常是因为文件路径不正确或文件不存在。以下是解决此问题的步骤:
步骤 1:检查文件路径
确保 error_logs.log
文件存在于你的项目目录中。你可以通过以下方法检查:
-
检查文件位置:
-
在 Windows 资源管理器中,导航到
D:\project\pythonProject
目录。 -
确认
error_logs.log
文件是否存在于该目录中。 -
使用绝对路径: 如果文件不在当前目录中,你需要提供文件的绝对路径。例如:
Python复制
log_file = r'D:\project\pythonProject\error_logs.log'
步骤 2:修改代码以使用绝对路径
将代码中的 log_file
变量修改为文件的绝对路径:
Python复制
log_file = r'D:\project\pythonProject\error_logs.log'
实验结果
-
原始日志示例:显示未清洗的日志内容。
-
清洗后的数据示例:显示清洗后的 DataFrame。
-
清洗后的数据统计:显示数据的基本信息。
-
错误类型统计:显示各错误类型的出现次数。
-
可视化图表:生成柱状图和饼图,展示错误类型的分布和比例。
总结
通过本次实验,我们成功使用 Python、Pandas 和 Jupyter Notebook 对杂乱的日志文件进行了清洗、分析和可视化。实验结果表明,这种方法能够有效地统计高频错误类型,并通过图表直观展示错误分布,为系统优化和问题定位提供了有力支持。
未来的工作可以扩展到更复杂的数据分析,例如按 IP 地址统计错误频率、按时间分析错误趋势等,以进一步提升系统的稳定性和性能。
作者:火批玩家