fre*_*ent 3 python apache logging parsing object
我坐在我的第一个python脚本上试图将apache日志解析为可访问的对象而我无法使其工作.
我正在尝试使用此示例(正在运行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
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么,但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*'
)
Run Code Online (Sandbox Code Playgroud)
通过该调整,您的示例匹配:
>>> 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': '-'}
Run Code Online (Sandbox Code Playgroud)