如何使用Python正则解析AWS ELB日志提取request、user_agent等字段
AWS ALB 日志字段提取正则(Python版)
以下正则可完整匹配AWS应用负载均衡(ALB)的全量访问日志字段,你需要的请求行、User-Agent等内容都可以通过捕获组直接提取,已通过你提供的示例日志验证可用。
可用代码示例
import re # 全量匹配ALB日志的正则表达式 alb_log_regex = r'([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*):([0-9]*) ([^ ]*)[:-]([0-9]*) ([-.0-9]*) ([-.0-9]*) ([-.0-9]*) (|[-0-9]*) (-|[-0-9]*) ([-0-9]*) ([-0-9]*) \"([^ ]*) ([^ ]*) (- |[^ ]*)\" \"([^\"]*)\" ([A-Z0-9-]+) ([A-Za-z0-9.-]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\" ([-.0-9]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^ ]*)\" \"([^\s]+?)\" \"([^\s]+)\" \"([^ ]*)\" \"([^ ]*)\"' # 测试日志行 test_log_line = 'h2 2021-06-07T23:57:13.300250Z app/megapool-retool-app/dbb257b8adaa87cf 93.107.2.244:59799 - -1 -1 -1 302 - 3087 561 "POST https://example.com:443/api/pages/uuids/8ad6e82e-f86b-11ea-a68d-cbc99f85d247/updateUserHeartbeat HTTP/2.0" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 arn:aws:elasticloadbalancing:us-west-2:752180062774:targetgroup/megapool-retool-app/1665e090211d92fc "Root=1-6089b259-1c8c6bca3b1d7a895a21a694" "xyz.com" "arn:aws:acm:us-west-2:75218123456562774:certificate/b7a45f0c-3009-42c2-97b9-ab81a61d1b25" 0 2021-06-07T23:57:13.299000Z "authenticate" "-" "-" "-" "-" "-" "-"' match_result = re.match(alb_log_regex, test_log_line) if match_result: # 提取完整请求行 full_request = f'"{match_result.group(15)} {match_result.group(16)} {match_result.group(17)}"' # 提取User-Agent user_agent = f'"{match_result.group(18)}"' print('完整请求行:', full_request) print('User-Agent:', user_agent) # 所有字段可按捕获组序号对应官方字段定义提取,核心常用字段对应关系: # 组1: 连接协议类型 # 组2: 请求时间 # 组3: ALB资源标识 # 组4: 客户端IP # 组5: 客户端端口 # 组15: 请求方法 # 组16: 请求URL # 组17: HTTP版本 # 组18: User-Agent # 组19: TLS加密套件 # 组20: TLS版本
注意事项
- 该正则仅适用于AWS应用负载均衡(ALB)的访问日志,不适用于经典负载均衡(CLB)、网络负载均衡(NLB)的日志格式。
- 如果日志存在未转义的特殊字符导致匹配失败,可根据实际日志格式微调捕获组的匹配规则。
内容的提问来源于stack exchange,提问作者Ripunjay Godhani
相关产品推荐
相关产品推荐

