feat: 实现日志解析和 404 错误分析

- 添加日志解析函数,使用正则表达式解析 Apache 日志
- 通过 Spark 读取和处理日志数据
- 实现 404 错误日志的过滤和统计- 获取并打印前 25 个产生 404错误最多的主机
This commit is contained in:
fly6516 2025-04-14 03:40:00 +08:00
parent e556d97aca
commit 1512ab8eeb

58
2-3.py Normal file
View File

@ -0,0 +1,58 @@
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 错误日志
error_404_logs = access_logs.filter(lambda log: log['status_code'] == 404).cache()
# 获取前 25 个产生 404 错误最多的主机
top_25_404_hosts = (
error_404_logs
.map(lambda log: (log['ip'], 1))
.reduceByKey(lambda a, b: a + b)
.takeOrdered(25, key=lambda x: -x[1])
)
# 打印结果
print("前 25 个产生 404 错误最多的主机:")
for i, (host, count) in enumerate(top_25_404_hosts):
print("{}: {} 次 404 错误".format(i + 1, host, count))
# 停止 Spark
sc.stop()