有没有办法让这个功能看起来更好?

时间:2013-08-02 16:25:11

标签: python

我需要一个从Apache日志文件中提取url的逻辑: 现在我这样做了:

apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'}
data = apache_log['@message'].split()
if data.index('"POST') and data[data.index('"POST')+2].startswith('HTTP'):
     print data[data.index('"POST')+1] 

它让我回复:

/user/12345/product/2

基本上结果是正确的,但我做的方式我并不喜欢。

有人可以建议更好(更Pythonic)从apache日志文件中提取此路径的方法。

1 个答案:

答案 0 :(得分:5)

正则表达式会更好用:

import re

post_path = re.compile(r'"POST (/\S+) HTTP')

match = post_path.search(apache_log['@message'])
if match:
    print match.group(1)

演示:

>>> import re
>>> apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'}
>>> post_path = re.compile(r'"POST (/\S+) HTTP')
>>> match = post_path.search(apache_log['@message'])
>>> if match:
...     print match.group(1)
... 
/user/12345/product/2