有分析nginx日志的需求,我也懒得去研究logstach之类的开源工具。我只是简单地写一个脚本,并根据需要自己实现它:
先看日志格式:我们和别人的不一样,没办法:
12.195.166.35[10/May/2015:14:38:09+0800]"list.xxxx.com""GET/new/10:00/9.html?cat=0,0&;sort=price_ASCHTTP/1.0"20042164"HTTP://list.Zhonghuasuan.com/new/10:00/8.html?cat=0,0&;sort=price_ASC""Mozilla/5.0(Linux;u;安卓4.4.2;zh-CN;h60-L02Build/hdh60-L02)appleWebKit/534.30(KHTML,像壁虎一样)版本/4.0UCBrowser/10.4.0.558U3/0.8.0MobileSafari/534.30"
以上是我的日志格式:
脚本如下:
#!/usr/bin/env python #-*- coding:utf-8 –*- #Author:xiaoluo #QQ:942729042 #date:2015:05:12 import re import sys log = sys.argv[1] ip = r"?P<ip>[\d.]*" date = r"?P<date>\d+" month = r"?P<month>\w+" year = r"?P<year>\d+" log_time = r"?P<time>\S+" timezone = r"""?P<timezone> [^\"]* """ name = r"""?P<name>\" [^\"]*\" """ method = r"?P<method>\S+" request = r"?P<request>\S+" protocol = r"?P<protocol>\S+" status = r"?P<status>\d+" bodyBytesSent = r"?P<bodyBytesSent>\d+" refer = r"""?P<refer>\" [^\"]*\" """ userAgent=r"""?P<userAgent> .* """ #f = open('access1.log','r') #for logline in f.readlines(): p = re.compile(r"(%s)\ \[(%s)/(%s)/(%s)\:(%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)\ (%s)" %(ip, date, month, year, log_time,timezone,name,method,request,protocol,status,bodyBytesSent,refer,userAgent), re.VERBOSE) def getcode(): codedic={} f = open(log,'r') for logline in f.readlines(): matchs = p.match(logline) if matchs !=None: allGroups =matchs.groups() status= allGroups最后一个功能是统计每分钟的访问量。 codedic[status]=codedic.get(status,0) +1 return codedic f.close() def getIP(): f = open(log,'r') IPdic={} for logline in f.readlines(): matchs = p.match(logline) if matchs !=None: allGroups =matchs.groups() IP=allGroups[0] IPdic[IP] = IPdic.get(IP,0) +1 IPdic=sorted(IPdic.iteritems(),key=lambda c:c[1],reverse=True) IPdic=IPdic[0:21:1] return IPdic f.close() def getURL(): f = open(log,'r') URLdic={} for logline in f.readlines(): matchs = p.match(logline) if matchs !=None: allGroups =matchs.groups() urlname = allGroups[6] URLdic[urlname] = URLdic.get(urlname,0) +1 URLdic=sorted(URLdic.iteritems(),key=lambda c:c[1],reverse=True) URLdic=URLdic[0:21:1] return URLdic def getpv(): f = open(log,'r') pvdic={} for logline in f.readlines(): matchs = p.match(logline) if matchs !=None: allGroups =matchs.groups() timezone=allGroups[4] time = timezone.split(':') minute = time[0]+":"+time[1] pvdic[minute]=pvdic.get(minute,0) +1 pvdic=sorted(pvdic.iteritems(),key=lambda c:c[1],reverse=True) pvdic=pvdic[0:21:1] return pvdic if __name__=='__main__': print "网站监控状况检查状态码" print getcode() print "网站访问量最高的20个IP地址" print getIP() print "网站访问最多的20个站点名" print getURL() print getpv()这里应该指出的是。在开始的时候,我单独封装了一个函数用于常规匹配,这样就省去了在打开后面的每个函数之前单独打开文件的需要。但是,当我返回时,我只能以列表的形式返回。结果,列表消耗了我太多的内存。我的有32G内存,15G日志。
效果:
[10]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)