From 9469f76e1a7f6e4eb71cc0ab9bf57516283b4acb Mon Sep 17 00:00:00 2001 From: fly6516 Date: Mon, 14 Apr 2025 03:49:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E7=BB=9F=E8=AE=A1=E6=AF=8F=E6=97=A5=20404?= =?UTF-8?q?=20=E9=94=99=E8=AF=AF=E8=AE=B0=E5=BD=95=E6=95=B0=E9=87=8F-=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=202-5.py=20=E6=96=87=E4=BB=B6=EF=BC=8C?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20Apache=20=E6=97=A5=E5=BF=97=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E5=92=8C=20404=20=E9=94=99=E8=AF=AF=E7=BB=9F=E8=AE=A1?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=20-=20=E4=BD=BF=E7=94=A8=20Spark=20=E8=AE=A1?= =?UTF-8?q?=E7=AE=97=E6=A1=86=E6=9E=B6=E5=A4=84=E7=90=86=E5=A4=A7=E8=A7=84?= =?UTF-8?q?=E6=A8=A1=E6=97=A5=E5=BF=97=E6=95=B0=E6=8D=AE=20-=20=E6=8F=90?= =?UTF-8?q?=E5=8F=96=E6=97=A5=E5=BF=97=E4=B8=AD=E7=9A=84=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=EF=BC=8C=E7=BB=9F=E8=AE=A1=E6=AF=8F=E6=97=A5?= =?UTF-8?q?=20404=20=E9=94=99=E8=AF=AF=E6=AC=A1=E6=95=B0=20-=20=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E6=8C=89=E6=97=A5=E6=9C=9F=E6=8E=92=E5=BA=8F=E5=B9=B6?= =?UTF-8?q?=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2-5.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 2-5.py diff --git a/2-5.py b/2-5.py new file mode 100644 index 0000000..85def17 --- /dev/null +++ b/2-5.py @@ -0,0 +1,61 @@ +import re +from pyspark import 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() + + print("每天 404 错误记录数量:") + for day, count in daily_404_stats: + print("Day {}: {} 次 404 错误".format(day, count)) + + sc.stop()