From e556d97acaf50d1443239376613b6d17ceedef00 Mon Sep 17 00:00:00 2001 From: fly6516 Date: Mon, 14 Apr 2025 03:35:39 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E5=92=8C404=20=E9=94=99=E8=AF=AF=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增日志解析函数 parse_log_line,用于解析 Apache 日志 - 添加过滤 404 错误的函数 filter_404 - 实现从 HDFS 读取日志、解析、过滤和统计 404 错误的完整流程- 打印 404 错误记录的数量 --- 2-2.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 2-2.py diff --git a/2-2.py b/2-2.py new file mode 100644 index 0000000..6a88d42 --- /dev/null +++ b/2-2.py @@ -0,0 +1,54 @@ +import re +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 + } + +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 错误日志的 RDD + error_404_logs = access_logs.filter(lambda log: log['status_code'] == 404).cache() + + # 获取最多 40 个不同的 endpoint + unique_404_endpoints = error_404_logs.map(lambda log: log['endpoint']).distinct() + top_40_endpoints = unique_404_endpoints.take(40) + + # 输出结果 + print("最多 40 个不同的 404 错误端点:") + for i, ep in enumerate(top_40_endpoints): + print("{}: {}".format(i + 1, ep)) + + # 停止 SparkContext + sc.stop()