首页 > 解决方案 > 如何根据apache access.log中的方法统计请求数

问题描述

我需要显示每种方法的请求数

来自 apache access.log 的行示例:

109.169.248.247 - - [12/Dec/2015:18:25:11 +0100] "POST /administrator/index.php HTTP/1.1" 200 4494 "http://almhuette-raith.at/administrator/" "Mozilla /5.0 (Windows NT 6.0; rv:34.0) Gecko/20100101 Firefox/34.0" 4374

这是代码:

import argparse
import json
import re
from collections import defaultdict

parser = argparse.ArgumentParser(description='access.log parser')
parser.add_argument('-f', dest='logfile', action='store', default='access.log')
args = parser.parse_args()

reg_meth =  r'(GET|POST|PUT|DELETE|HEAD)'
dict_meth = defaultdict(lambda: {"GET": 0, "POST": 0, "PUT": 0, "DELETE": 0, "HEAD": 0})

with open(args.logfile) as f:
  for line in f.readlines:
       methods =  re.search(reg_meth, line).groups()[0]
       dict_meth[methods] += 1
print(json.dumps(dict_meth, indent=4))

执行代码时,出现错误:

dict_method[method] += 1
TypeError: unsupported operand type(s) for +=: 'dict' and 'int'

所以,代码不起作用。我该如何解决?

标签: python-3.xparsingre

解决方案


推荐阅读