前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 正则分析nginx日志

python 正则分析nginx日志

作者头像
py3study
发布2020-01-03 15:52:58
6790
发布2020-01-03 15:52:58
举报
文章被收录于专栏:python3python3

  有个需求要分析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_asc HTTP/1.0" 200 42164 "http://list.zhonghuasuan.com/new/10:00/8.html?cat=0,0&sort=price_asc" "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; H60-L02 Build/HDH60-L02) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/10.4.0.558 U3/0.8.0 Mobile Safari/534.30"

上面是我的日志格式:

脚本如下:

代码语言:javascript
复制
#!/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[10]
             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()

这里要指出的是。我当初是给正则匹配的时候单独封装一个函数的,这样就省去了下面每个函数要打开之前都要单独打开一遍文件,但是我return的时候只能用列表的形式返回,结果列表太大把我的内存耗光了,我的是32G的内存,15G的日志。

效果:

wKioL1VTFI2jFdrgAAMgZdOMGos474.jpg
wKioL1VTFI2jFdrgAAMgZdOMGos474.jpg

最后一个函数是统计每分钟,访问的数量

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云拨测
云拨测(Cloud Automated Testing,CAT)利用分布于全球的监测网络,以真实终端用户使用场景为视角,提供模拟终端用户体验的拨测服务。CAT 可实现对网络质量、页面性能、端口性能、文件传输、音视频体验等场景进行周期性监控,支持多维度分析性能指标。利用可视化性能数据和告警通知可帮助您及时对业务质量作出反应,保证业务稳定正常运行。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档