2

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

基本的に結果は正しいのですが、私のやり方はあまり好きではありません。

Apache ログ ファイルからこのパスを抽出するより良い (より Pythonic な) 方法を誰かが提案できますか。

4

1 に答える 1

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
于 2013-08-02T16:28:12.120 に答える