From ede4f6c21fea1dc83a079d5e55664495a7ee6544 Mon Sep 17 00:00:00 2001 From: fly6516 Date: Mon, 14 Apr 2025 03:51:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E7=BB=98=E5=88=B6=E6=AF=8F=E6=97=A5=20404?= =?UTF-8?q?=20=E5=93=8D=E5=BA=94=E4=BB=A3=E7=A0=81=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E7=9A=84=E6=8A=98=E7=BA=BF=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增2-6.py 文件,实现日志解析和统计功能 - 使用 Spark 集群处理大规模日志数据 - 提取每日404 错误次数并使用 Matplotlib 绘制折线图 - 通过正则表达式解析日志,过滤出404 状态码的日志 - 按日期统计404 错误次数,并排序 - 最后展示折线图,直观显示每日 404 错误的变化趋势 --- 2-6.py | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2-6.py diff --git a/2-6.py b/2-6.py new file mode 100644 index 0000000..1862def --- /dev/null +++ b/2-6.py @@ -0,0 +1,79 @@ +import re +import matplotlib.pyplot as plt +from pyspark import SparkContext + +# 初始化 SparkContext +sc = SparkContext.getOrCreate() + +# 日志匹配的正则表达式 +LOG_PATTERN = re.compile( + r'^(\S+) (\S+) (\S+) \[([\w:/]+\s[+-]\d{4})\] "(\S+) (\S+)\s*(\S*)\s?" (\d{3}) (\S+)' +) + +# 解析日志的函数 +def parse_log_line(line): + match = LOG_PATTERN.match(line) + if not match: + return None + + content_size_str = match.group(9) + content_size = int(content_size_str) if content_size_str.isdigit() else 0 + + return { + 'ip': match.group(1), + 'user_identity': match.group(2), + 'user_id': match.group(3), + 'timestamp': match.group(4), + 'method': match.group(5), + 'endpoint': match.group(6), + 'protocol': match.group(7), + 'status_code': int(match.group(8)), + 'content_size': content_size + } + +def extract_day(log): + # 时间格式为:10/Oct/2000:13:55:36 -0700 + full_date = log['timestamp'] + day = full_date.split('/')[0] # 只提取日 + return day + +if __name__ == "__main__": + # 加载日志文件 + logFile = "hdfs://master:9000/user/root/apache.access.log.PROJECT" + raw_logs = sc.textFile(logFile) + + # 解析并过滤有效日志 + access_logs = raw_logs.map(parse_log_line).filter(lambda x: x is not None).cache() + + # 过滤 404 状态码的日志 + error_404_logs = access_logs.filter(lambda log: log['status_code'] == 404).cache() + + # 每日 404 次数统计 + errDateSorted = ( + error_404_logs + .map(lambda log: (extract_day(log), 1)) + .reduceByKey(lambda a, b: a + b) + .sortByKey(True) + .cache() + ) + + # 收集结果 + daily_404_stats = errDateSorted.collect() + + # 提取日期和404次数 + days = [day for day, _ in daily_404_stats] + counts = [count for _, count in daily_404_stats] + + # 使用 matplotlib 绘制折线图 + plt.figure(figsize=(10, 6)) + plt.plot(days, counts, marker='o', color='b', linestyle='-', linewidth=2, markersize=6) + plt.title("每日 404 响应代码记录") + plt.xlabel("日期") + plt.ylabel("404 错误次数") + plt.xticks(rotation=45) + plt.grid(True) + plt.tight_layout() + plt.show() + + # 停止 Spark + sc.stop()