Web服务器的各种系统管理工作包括了多Nginx/Apache 日志的统计,python使这个任务变得极其简单,下面分享两个小脚本。
一、统计Nginx的客户端缓存的命中率
需要检查你的Nginx服务器拒绝客户请求的频率,服务器拒绝的原因是因为客户缓存中的页面已经更新过了。
解决方案:
当浏览器请求一个在它的缓存中的服务器页面时,浏览器首先会让服务器了解缓存数据,如果客户缓存是更新过的,服务器会返回一个特殊的错误码(而不是再次提供该页面)。下面是在服务器的日志中统计这种现象的代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/env python
import
sys
logfile
=
sys.argv[
1
]
def
ClientCache(logfile_path):
contents
=
open
(logfile,
"r"
)
totalrequests
=
0
cacherequests
=
0
for
line
in
contents:
totalrequests
+
=
1
if
line.split(
" "
)[
8
]
=
=
"304"
:
cacherequests
+
=
1
print
"Percentage of requests that were client-cached: "
,
str
(cacherequests)
+
"%"
|
运行结果如下:
1
2
|
[root@chlinux logs]# ./nginx_log.py access.log
Percentage of requests that were client-cached: 17%
|
讨论:
服务器的服务请求在客户端的缓存中的比例是衡量服务器效能的一个重要的因素。此脚本的代码能帮你从服务器日志中获取这种信息。
此脚本的代码利用循环,每次读取日志文件中的一行,这也是读取文件的常用方式。for循环的主体部分调用split 方法来切割行字符串,它使用一个单空格字符串作为参数,将整行切成了由空格隔开的字段,并组成一个元组,然后它使用索引([8])来获取第9个字段。
二、检查Nginx的访问日志,统计基于每个独立IP地址的点击率
检查Nginx的日志文件,统计基于每个独立IP地址的点击率,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/env python
#coding:utf8
import
re
import
sys
contents
=
sys.argv[
1
]
def
NginxIpHite(logfile_path):
#IP:4个字符串,每个1到3个数字,由点连接
ipadd
=
r
'\.'
.join([r
'\d{1,3}'
]
*
4
)
re_ip
=
re.
compile
(ipadd)
iphitlisting
=
{}
for
line
in
open
(contents):
match
=
re_ip.match(line)
if
match:
ip
=
match.group( )
#如果IP存在增加1,否则设置点击率为1
iphitlisting[ip]
=
iphitlisting.get(ip,
0
)
+
1
print
iphitlisting
NginxIpHite(contents)
|
运行结果如下:
1
2
|
[root@chlinux
06
]
# ./nginx_ip.py access_20130617.log
{
'183.3.121.84'
:
1
,
'182.118.20.184'
:
2
,
'182.118.20.185'
:
1
,
'190.52.120.38'
:
1
,
'182.118.20.187'
:
1
,
'202.108.251.214'
:
2
,
'61.135.190.101'
:
2
,
'103.22.181.247'
:
1
,
'101.226.33.190'
:
3
,
'183.129.168.131'
:
1
,
'66.249.73.29'
:
26
,
'182.118.20.202'
:
1
,
'157.56.93.38'
:
2
,
'219.139.102.237'
:
4
,
'220.181.108.178'
:
1
,
'220.181.108.179'
:
1
,
'182.118.25.233'
:
4
,
'182.118.25.232'
:
1
,
'182.118.25.231'
:
2
,
'182.118.20.186'
:
1
,
'174.129.228.67'
:
20
}
|
此脚本返回的是一个字典,其中包含了访问Nginx 服务器的各个IP的点击数,这是通过分析Nginx日志文件的来的.在这个脚本中我们使用正则表达式来获得并同时验证IP,这个方法避使得我们避免了字符串切分操作和长度检查,但我们却不得不负担匹配正则表达式运行的开销。
本文转自1594cqb 51CTO博客,原文链接:http://blog.51cto.com/wolfchen/1224779,如需转载请自行联系原作者