#!/usr/bin/env python
# -*- coding: UTF8-*-
# author by ywr

import sys
import re

LOGFILE = "host.access.log"
LONGTIMEFILE = "longtime.log.txt"

##分析日志函数
def analyseLog(starttime,endtime):
    #print starttime,"--",endtime
    pattern = "^[0-9]{2}\:[0-9]{2}$"
    if re.match(pattern,starttime) is None or re.match(pattern,endtime) is None:
        print "the iuput parameter is wrong, should like 09:15"
    else:
        starthour = int(starttime.split(":")[0])
        startminute = int(starttime.split(":")[1])
        ##把时间统一转化成数字
        startcount = starthour * 60 + startminute
        #print startcount
        endhour = int(endtime.split(":")[0])
        endminute = int(endtime.split(":")[1])
        endcount = endhour * 60 + endminute
        #print endcount
        ##打开日志文件
        logfile = open(LOGFILE,"r")
        longtimefile = open(LONGTIMEFILE,"wb")
        longtimefile.write("ip------time------request--------http code-----response time\n\n")

        ##开始分析日志
        accessline = logfile.readline()
        lines = 0
        while accessline :
            ##以空格分割字符串
            columns = accessline.split(" ")
            ##获取时间,并转化为数字来表示大小
            linetime = columns[3]
            linehour = int(linetime.split(":")[1])
            lineminute = int(linetime.split(":")[2])
            linecount = linehour * 60 + lineminute
            ##获取响应时间
            responsetime = float(columns[len(columns) - 1].replace('"',"").replace("\n",""))

            ##取响应时间大于3s的请求
            if linecount>=startcount and linecount<=endcount and responsetime >=5:
                linestr = columns[0] + " " + columns[3].replace("[","") + " " + columns[6]  + " " + columns[8] + " " + columns[len(columns)-1] + "\n"
                longtimefile.write(linestr)
                lines += 1

            ##重复读入记录行
            accessline = logfile.readline()

        ###while end

        ##关闭文件
        longtimefile.write("exception lines: "+str(lines))
        logfile.close()
        longtimefile.close()

    return "ok"


###main function
if __name__ == "__main__":
    if len(sys.argv) != 3 :
        print "please input two parameters(starttime endtime), like 09:15 10:10"
    else:
        starttime = sys.argv[1]
        endtime = sys.argv[2]
        analyseLog(starttime,endtime)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐