# 公司网站反映很慢,可能是一些页面的访问方法或者页面引起,通过程序统计nginx访问日志的页面和具体的action方法访问次数以及平均响应时间可以为程序开发的同事提供参考定位具体的代码


# 默认的nginx日志

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

现在加上响应时间,方便统计

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$http_host" "$upstream_response_time" "$request_time"' ;

发现统计出来的响应时间$upstream_response_time无法参与计算,于是去掉引号,变为如下,方便计算:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$http_host" $upstream_response_time $request_time';

不需要去掉双引号也可以,用python处理一下去掉两边的双引号即可,如下:

_time = _time.lstrip('"').rstrip('"')

具体的python代码

#encoding=utf-8

from decimal import Decimal
# 找到日志中的top n,日志格式如下
# 192.168.5.46 - - [01/Dec/2017:09:47:21 +0800] "GET /api_moblie_idol.php?action=get_user_guangying_comment&app_platform=android&channelId=S007&starid=6730&version=164&unique_id=A73308A15313C8E34B518CA515288A13&messageid=5a20ae347a11737a288b4738&gtui_cid=03908d9fa39c8de124aa01688109b26c&page=7&type=latest HTTP/1.0" 200 70 "-" "-" "223.89.74.82" "data.android.idol001.com" 0.050 0.052
# 统计访问网站php页面和方法的次数,并且生成响应时间
def log_analysis(log_file, dpath, topn = 10):
path=log_file
shandle = open(path, 'r')
count = 1 log_dict = {}
log_dict2 = {}
total_time = 0.0 while True:
     # 最好加上strip()碰到换行就无法识别了
line = shandle.readline().strip()
# 如果到了文件末尾就终止
if line == '':
break
nodes = line.split() # 192.168.9.187 - - [30/Nov/2017:18:28:35 +0800] "GET /api_moblie_idol.phpnique_id=5ACE6943 HTTP/1.0" 200 13950 "-" "idol/5900 (iPhone; iOS 10.3.2; Scale/3.00)" "171.221.169.54" "data.idol001.com" "0.144" "0.144" _url, _time = nodes[6], nodes[-2] # 使用?分割页面,获取url,通过action和&分割出action动作
_tmp = _url.split('action')
if len(_tmp) != 2:
continue
_url = _url.split('?')[0] _method = _tmp[1].split('&')[0] # print 'url:%s, method:%s, time:%s' % (_url,_method,_time) # 如果不是数字就跳出本次循环
if _time == '-':
continue try:
# {(url,method):count}当做字典的key
# 统计url,method的次数
if (_url, _method) not in log_dict:
log_dict[(_url, _method)] = 1
else:
log_dict[(_url, _method)] = log_dict[(_url, _method)] + 1 # 统计url,method的累计时间 if (_url, _method) not in log_dict2:
log_dict2[(_url, _method)] = Decimal(_time)
else:
log_dict2[(_url, _method)] = Decimal(_time) + Decimal(log_dict2[(_url, _method)])
except Exception,e:
continue # print log_dict
# print log_dict2
# 关闭文件句柄
shandle.close()
# 对字典进行排序
# ('/index', 'post'): 2
rst_list = log_dict.items()
# print rst_list for j in range(topn):
# 冒泡法根据rst_list中的count排序,找出访问量最大的10个IP
for i in range(0,len(rst_list) - 1):
if rst_list[i][1] > rst_list[i+1][1]:
temp = rst_list[i]
rst_list[i] = rst_list[i+1]
rst_list[i+1] = temp # 获取 topn 个数
need_list = rst_list[-1:-topn - 1:-1] rt_list = []
for _line, _num in need_list:
_tmp_dict = {}
_avg_time = Decimal(log_dict2[_line])/Decimal(_num)
# print '_avg= %s' % _avg_time
_tmp_dict['_num'] = _num
_tmp_dict['_avg'] = _avg_time
rt_list.append((_line,_tmp_dict)) # print rt_list
# 打印出top 10访问日志,并写入网页中
title = 'nginx访问日志'
tbody = ''
for k,v in rt_list:
print v['_num'],k[1],k[0],v['_avg']
tbody += '<tr>\n<td>%s</td><td>%s</td><td>%s</td><td>%s</td>\n<tr>\n' % (v['_num'],k[1],k[0],v['_avg']) html_tpl = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{title}</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0" color='pink'>
<thead>
<tr cellspacing="0" cellpadding="0">
<th>访问次数</th>
<th>method</th>
<th>url</th>
<th>平均响应时间</th>
</tr>
</thead>
{tbody}
</table>
</body>
</html>
'''
html_handle = open(dpath,'w')
html_handle.write(html_tpl.format(title = title, tbody = tbody))
html_handle.close() # 函数入口
if __name__ == '__main__':
# nginx日志文件
log_file = 'access_android_idol001_com.log'
dpath = 'top1000.html'
# topn 表示去top多少个
# 不传,默认10个
topn = 1000
log_analysis(log_file,dpath,topn)

最终的效果:

通过python统计nginx日志定位php网站响应慢的问题的更多相关文章

  1. 使用Python 统计nginx日志前十ip访问量并以柱状图显示

    脚本内容: import matplotlib.pyplot as plt # nginx_file = '10.6.11.91_access.log-2018-12-27' ip = {} #筛选n ...

  2. 统计nginx日志里流量

    用awk可以,比如,我想统计nginx日志里,今天下午3点0分,这一分钟内,访问的流量(文件的大小) grep "07/Nov/2013:15:00:"  *.log|awk '{ ...

  3. Python切割nginx日志_小组_ThinkSAAS

    Python切割nginx日志_小组_ThinkSAAS Python切割nginx日志

  4. 统计nginx日志

    .根据访问IP统计UV awk '{print $1}' access.log|sort | uniq -c |wc -l .统计访问URL统计PV awk '{print $7}' access.l ...

  5. linux统计nginx日志中请求访问量命令

    Nginx 三种分配策略:轮询.权重.ip_hash(比如你登录了一个网站,登录信息已经保存到 a 机器,但当你做后续操作时的请求会到 b 机器,那么就获取不到你原来登录的信息,此时你就需要重新登录了 ...

  6. 利用python分析nginx日志

    最近在学习python,写了个脚本分析nginx日志,练练手.写得比较粗糙,但基本功能可以实现. 脚本功能:查找出当天访问次数前十位的IP,并获取该IP来源,并将分析结果发送邮件到指定邮箱. 实现前两 ...

  7. 统计nginx日志单IP访问请求数排名

    下面是我截取一段nginx日志 /Jan/::: +] "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gec ...

  8. Grafana和influxdb监控nginx日志中的请求响应时间图形化监控

    监控效果如图: 监控方法: 通过logstash过滤nginx日志,然后解析出nginx日志中的request time字段 然后output到influxdb时序数据库中 通过grafana展示数据 ...

  9. python统计nginx脚本信息

    #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import subprocess import th ...

随机推荐

  1. centos nginx gerrit

    gerrit官方地址:https://www.gerritcodereview.com/ 需先安装依赖  jdk mysql 并手动创建数据库 下载好war包后,初始化操作 java -jar ger ...

  2. HDU - 6313 Hack It(构造)

    http://acm.hdu.edu.cn/showproblem.php?pid=6313 题意 让你构造一个矩阵使得里面不存在四个顶点都为1的矩形,并且矩阵里面1的个数要>=85000 分析 ...

  3. ArcGIS坐标系转换出错:Error 999999执行函数出错 invalid extent for output coordinate system

    本文主要介绍在用ArcGIS做坐标系转换过程中可能会遇到的一个问题,并分析其原因和解决方案. 如下图,对一份数据做坐标系转换: 过了一会儿,转换失败了.错误消息如下: “消息”中提示,“执行函数出错 ...

  4. 【十四】jvm 性能调优实例

    实例1: POI Excel 导出 Excel对象很大,多人同时登录系统导出Excel的话,就会有多个大Excel对象到老年代,这是老年代需要回收,系统可能会卡顿. jvm堆内存设置的越大,Full ...

  5. 【三】Eureka服务注册与发现

    1.是什么 Eureka是Netflix的一个子模块,也是核心模块之一.Eureka是一个基于 REST 服务,用于定位服务,以实现云端中间层服务发现和故障转移.服务注册与发现对于微服务架构来说是非常 ...

  6. 使用js代码将HTML Table导出为Excel

    使用js代码将HTML Table导出为Excel的方法: 直接上源码 <html> <head> <meta http-equiv="Content-Type ...

  7. 【python小练】0004

    第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数. 先回忆一下各种括号的用途: () tuple [] list {} dict ([]) set——需要一个list作为输入合集 c ...

  8. 【noip 2015】普及组

    T1.金币 题目链接 #include<cstdio> #include<algorithm> #include<cstring> using namespace ...

  9. 小程序开发-Step1

    先申请一个小程序 https://mp.weixin.qq.com/wxopen/waregister?action=step1 根据以上链接步骤一步一步来,认识字就可以完成,没什么特殊的 申请成功之 ...

  10. Flask里面的cookie的基本操作

    #cookie相关操作,依赖于make_response #调用cookie依赖request模块 from flask import Flask,make_response,request #建立对 ...