【问题标题】:How to use regex to parse log to list如何使用正则表达式解析日志以列出
【发布时间】:2020-06-22 09:29:36
【问题描述】:

我尝试将此日志解析为 pandas 数据框。我需要使用正则表达式将此日志解析为带有 python 的列表/数据框,谢谢

127.0.0.1 - - [05/Feb/2012:17:11:55 +0000] "GET / HTTP/1.1" 200 140 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19"

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

此日志来自Understanding Apache's access log

我尝试过拆分和 for 循环,但它很奇怪。正则表达式会更有效,你知道它是否可能以及如何?

node = re.search(regex, log_line).group(1)
node = node.split(" ")
print(node)

【问题讨论】:

  • 在问题中显示您尝试的格式正确的代码。
  • 是的,我不知道使用哪个正则表达式

标签: python regex python-3.x logging


【解决方案1】:
APACHE_LOG_PATTERN = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] \"(\S+) (\S+)\s*(\S+)?\s*\" (\d{3}) (\S+)'
match = re.search(APACHE_LOG_PATTERN, l)
host          = match.group(1)
client_id     = match.group(2)
user_id       = match.group(3)
date_time     = match.group(4)#%Y/%m/%d:%I:%M:%S +0100
method        = match.group(5)
endpoint      = match.group(6)
protocol      = match.group(7)
response_code = int(match.group(8))
content_size  = match.group(9)

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多