提取日志文件的指定内容

 

如下日志,提取出Notice:开头的行中的ctime的值,然后求平均数

a.log日志文件

Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
112222221111111122233331111111111111
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
hhhhhhhhhhhhhhhhhhhhhhhhh
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r


Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r


Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r

Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r

Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r

Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r
Notice:hjhj hjj  hj  hj j h j hh ctime:35s fr  fr f rf r fr f r

 

解决方法

#coding=utf-8
import re

def gettime(l):
    num=""
    index=int(l.find("ctime"))+6
    while(True):
        if(l[index]=="s"):
            break
        else:
            num+=l[index]
        index+=1
    return int(num)

t=0
count=0
with open("a.log","r") as f:
    while(True):
        l=f.readline()
        if(not l):
            break
        if(re.match("Notice:",l)):
            t+=gettime(l)
            count+=1
    average=t/count
    print(average)

输出

35.0

 

 

 

 

上一篇:MySQL5.7 多实例


下一篇:SSH通道来访问MySQL