python - 如何将单个 apache 日志条目解析为 python 对象

标签 python apache parsing object logging

我正在处理我的第一个 python 脚本,试图将 apache 日志解析为可访问的对象,但我无法让它工作。

我正在尝试使用 this示例(运行 Python 2.7)并且只想让它与单个日志条目一起工作。

这是我的:

import re
from collections import namedtuple

format_pat= re.compile( 
    r"(?P<host>[\d\.]+)\s" 
    r"(?P<identity>\S*)\s" 
    r"(?P<user>\S*)\s"
    r"\[(?P<time>.*?)\]\s"
    r'"(?P<request>.*?)"\s'
    r"(?P<status>\d+)\s"
    r"(?P<bytes>\S*)\s"
    r'"(?P<referer>.*?)"\s'
    r'"(?P<user_agent>.*?)"\s*' 
)

Access = namedtuple('Access',
    ['host', 'identity', 'user', 'time', 'request',
    'status', 'bytes', 'referer', 'user_agent'] )

# my entry
log = '2001:470:1f14:169:15f3:824f:8a61:7b59 - ABC-15414 [14/Nov/2012:09:32:31 +0100] "POST /setConnectionXml HTTP/1.1" 200 4 "-" "-" 102356'

match= format_pat.match(log) 
print match

if match:
   Access( **match.groupdict() )
   print Access

我不确定我做错了什么,但是 match 返回 none,而不是我希望的对象。

有人可以给我提示吗?

最佳答案

您的 host 条目仅匹配数字和点(IPv4 地址),但您发布的日志条目示例是 IPv6 地址。调整您的模式以允许该格式(因此要么匹配数字和点,要么匹配十六进制字符和冒号:

format_pat= re.compile( 
    r"(?P<host>(?:[\d\.]|[\da-fA-F:])+)\s" 
    r"(?P<identity>\S*)\s" 
    r"(?P<user>\S*)\s"
    r"\[(?P<time>.*?)\]\s"
    r'"(?P<request>.*?)"\s'
    r"(?P<status>\d+)\s"
    r"(?P<bytes>\S*)\s"
    r'"(?P<referer>.*?)"\s'
    r'"(?P<user_agent>.*?)"\s*' 
)

通过该调整,您的示例匹配:

>>> format_pat.match(log).groupdict()
{'status': '200', 'bytes': '4', 'request': 'POST /setConnectionXml HTTP/1.1', 'host': '2001:470:1f14:169:15f3:824f:8a61:7b59', 'referer': '-', 'user': 'ABC-15414', 'time': '14/Nov/2012:09:32:31 +0100', 'identity': '-', 'user_agent': '-'}

关于python - 如何将单个 apache 日志条目解析为 python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15225934/

相关文章:

c++ - Protocol Buffer 文本格式解析器在反斜杠字符上给出错误

Java 维基文本解析器

python - 在 app.yaml 中使用登录设置对 gae 进行单元测试

python - 如何将二维码分割成单独的图像?

python - 搜索并替换 HTML 文本,而不是标签

java - Hadoop:对文件进行分组以进行映射

parsing - SID文件格式解析

python - Django 找不到模板目录

java - 如果值为 null 或空,如何使用 Apache Velocity 模板生成自关闭 XML 元素

php - 在 apache linux 中将子文件夹设为子域形式