python试用-日志统计
最近两天尝试用python代替bash写Linux Shell脚本来统计日志。发现python写起来比bash更简单和容易阅读,发现不少惊喜。所以写了一个粗糙的脚本来统计日志。
目标
1、通过简单命令和脚本统计事件发生数
2、日志限定文本类型
假定环境
日志文件:1.log
test:aaa,1
test:bbc,1
test:bbc,2
test:bba,2
test:baa,3
test:baa,1
other1:xx,bb,3
other2:32
日志文件:2.log
test:ab,2
other3:123
统计脚本
log_static.py
统计脚本
1 #!/usr/bin/python
2 import sys
3 #1st arg for tag key
4 key = "test:" if len(sys.argv) > 2; else sys.argv[1]
5 #2nd arg for split signal
6 split = "," if len(sys.argv) > 3 else sys.argv[2]
7 #3rd arg for static index
8 stat_idx = 0 if len(sys.argv) > 4 else int(sys.argv[3])
9 key_map = {}
10 #loop for read
11 while True:
12 #reading line from piple
13 line = sys.stdin.readline()
14 line = line[:-1] if line.endswith("\n") else line
15 if len(line) == 0:
16 break
17 #find current key to static
18 cur_key = line.split(key)[1].split(split)[stat_idx]
19 #update static
20 key_map[cur_key] = key_map[cur_key] + 1 if(key_map.has_key(cur_key)) else 1
21
22 #sort the map
23 result = sorted(key_map.items(), lambda x,y: cmp(y[1],x[1]))
24 #print out
25 for key,value in result:
26 print "%s,%s" % (key,value)
运行
添加执行权限:chmod + log_static.py
选择关键标签"test:",日志值分隔符为","
统计第一位发生次数:grep "test" *.log | ./log_static.py test: , 0 > 1.cvs
统计第二位发生次数:grep "test" *.log | ./log_static.py test: , 1 > 2.cvs
结果
统计文件:1.cvs
bbc,2
baa,2
ab,1
aaa,1
bba,1
统计文件:2.cvs
1,3
2,3
3,1
备注
#!/usr/bin/python python库引用
import sys 导入系统组建
sys.argv 调用参数
target = value 1 if (statement) else value2 相当于target = statement ? value 1 : value2
python的通过缩进判断分块,没有结束符号
while (statement) True:
#code here
设置arr = [1,2,3,4],arr[:-2]筛选变为[1,2] 除了筛选还可以赋值arr[0 for x in range(0, 10)]
lambda x,y : cmp(y[1], x[1]) lambda运算,表述传入参数x,y 返回y[1]和x[1]的比较值(倒序)
for x,y in list 表示枚举list的每一项(item),其中x取值item[0],y取值item[1]
print "%s,%s" % (x,y) 格式化打印,%s代表该位置的字符串类型

浙公网安备 33010602011771号