设为首页 收藏本站
查看: 614|回复: 0

[经验分享] python分析nginx日志,每分钟nginx请求超过10ms的比例

[复制链接]

尚未签到

发表于 2018-11-12 06:55:33 | 显示全部楼层 |阅读模式
代码如下:  
#!/usr/bin/python
  
# --*-- coding:utf-8 --*--
  
import time
  
import datetime
  
import sys
  
import os
  
import os.path
  
import re
  
import json
  
import socket
  
import requests
  
import subprocess
  

  

  
class NginxLog(object):
  def __init__(self, log_file, seek_file):
  self.log_file = log_file
  self.seek_file = seek_file
  

  

  def hostname(self):
  """host_name: 主机名"""
  host_name = socket.gethostname()
  return host_name
  

  def writeSeek(self, seek):
  """读过的游标写入临时文件"""
  with open(self.seek_file,'w') as f:
  f.write(time.strftime("%Y-%m-%d %H:%M:%s", time.localtime(time.time())) + '\n')
  f.write(str(seek) + "\n")
  

  def LogRead(self):
  """读出新生成的日志
  # 如果第一次运行,或是删除临时文件,从头运行,否则,从上次读取之后运行
  # 0代表从头开始,1代表当前位置,2代表文件最末尾位置
  chunk: 返回一行日志
  """
  

  if os.path.exists(self.seek_file):
  with open(self.seek_file) as f:
  seek_tmp = f.readlines()
  seek_old = int(seek_tmp[1].strip())
  else:
  seek_old = 0
  with open(self.log_file) as f:
  #记录当前最新文件游标
  f.seek(0,2) #最新游标位置
  seek_now = f.tell()
  # 读取上次读完之后的日志
  if seek_now >= seek_old:
  f.seek(seek_old,0) #从文件开头位置偏移
  chunk = f.read(seek_now - seek_old)
  #如果seek_now-seek_old小于0说明日志轮训
  else:
  f.seek(0,0)
  chunk = f.read(seek_now)
  

  # 将这次的游标写入临时文件
  self.writeSeek(seek_now)
  return chunk
  

  def Log_percent(self):
  """获取分钟超过10ms请求数的百分比
  low_request_time: 低于10ms的请求数
  high_request_time: 高于10ms的请求数
  """
  

  low_request_time = []
  high_request_time = []
  

  for line in self.LogRead().split('\n'):
  tmp_time = line.split(' ')[-1]
  if tmp_time:
  tmp_data = float('%.3f' % float(tmp_time))
  request_time = int(tmp_data * 1000)
  if request_time > 10:
  high_request_time.append(request_time)
  else:
  low_request_time.append(request_time)
  # 一分钟请求总数
  count = float(len(low_request_time) + len(high_request_time))
  

  # 超过10ms的百分比
  if count:
  result = float(len(high_request_time))/count
  #只取分子
  percent = int(result * 100)
  return percent
  else:
  return 0#当一分钟请求数为0时,返回0
  

  def push_falcon(self, data, url):
  """数据推送到openfalcon"""
  host = self.hostname()
  current_time = int(time.time())
  payload = [
  {
  "endpoint": host,
  "metric": "nginx_request_percent",
  "timestamp": current_time,
  "step": 60,
  "value": data,
  "counterType": "GAUGE",
  "tags": "nginx_request_percent=10ms",
  }
  ]
  

  json_data=json.dumps(payload)
  print json_data
  res = requests.post("http://127.0.0.1:1988/v1/push", data=json_data)
  

  
def main():
  # 日志文件位置
  log_file = "/root/access.log"
  seek_file = "/root/seek_temp.log"
  url = "http://127.0.0.1:1988/v1/push"
  nginx_log = NginxLog(log_file,seek_file)
  percent = nginx_log.Log_percent()
  nginx_log.push_falcon(percent,url)
  

  
if __name__ == '__main__':
  main()



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.iyunv.com/thread-633833-1-1.html 上篇帖子: Keepalived 高可用ipvs和nginx服务 下篇帖子: nginx: [alert] kill(1726, 1) failed
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表