我正在解析大型 Apache 日志,例如:
example.com:80 1.2.3.4 - - [01/Jul/2021:06:12:12 +0000] "GET /test/example/index.php?a=b&c=d HTTP/1.1" 302 486 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.3945.117 Safari/537.36"
和:
import apache_log_parser, shlex
parser = apache_log_parser.make_parser("%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"")
with open("access.log") as f:
for l in enumerate(f):
x = parser(l)
对于每条线路,大约需要 0.1 毫秒(i5 笔记本电脑)/~0.9 毫秒(低端 Atom CPU N2800 1.86GHz)
这非常慢:每条线路将近 1 毫秒!所以我决定自己解析
shlex
(它很好地处理了引号等first "second block" "third block" fourth
)。
情况更糟!我得到,每行,~0.3 ms(i5 笔记本电脑)/~1.6ms 低端服务器with open("access.log") as f: for l in enumerate(f): x = shlex.split(l)
问题:哪种更快的方法(可能使用直接正则表达式?)可以允许解析此类日志?我只需要
server port ip datetime url status bytes referer useragent
。