这篇文章是Python拆分Apache日志,得到访问量、热门资源、出错比例、日志大小等统计信息。
一、统计网站的访问量
利用split函数对apache日志进行拆分,下标为0的是用户的ip,将ip添加到ips列表中。ips列表的长度就是网站的访问量PV。ips列表再保存到一盒集合中,集合天然就有去重功能,得到UV独立访问数


二、统计网站的热门资源
请求的资源在第七个字段(序号6),Counter的most_common函数可用来显示最大的几个元素,十分方便的完成热门资源的定位。
由于%格式化字符串可能在以后的版本启用,可用改为format来格式化输出:
print("请求的资源:{0:30} \t 访问数量:{1} " .format(item[0],item[1]))

运行结果:

三、统计网站的出错比例
HTTP的状态码大于400视为出错,利用字典来保存状态码(key)和数量(value),出错比例等于出错除以访问总数。

运行结果:

四、统计Apache日志的大小
统计当前目录下(或者定位为绝对路径)以access.log开头的文件的总大小,并使用函数bytes2human转换为易读的单位。

运行结果如下:

网友评论