使用Python实现的Nginx日志监控程序

目前业务系统对外访问服务以4台WEB应用做集群,通过Nginx做负载。因为有用户在使用后台系统的SQL查询功能,编写的不合理SQL语句往往会导致所在的那台WEB应用异常卡顿,一旦外部访问Nginx的服务器时,分配到那台卡顿的WEB应用时,访问的质量非常差,这时候往往只能通过用户反馈前端访问很卡。为了做到及时预警,用Python写了一个简单监控Nginx日志的程序。

#!/usr/bin/python
#--*coding:utf-8 -*-

'''
auth:linuxidc
desc:监控Nginx后端服务响应的状态,一旦响应时间超过10ms,累计次数超过10次,将通过邮件告警
date:2016-12-06

remake:因为nginx每天23:59分会做一次备份,旧的access.log会被临时删掉,一旦删掉该监控程序将会
失效(问题暂时还不能通过python自身解决),只能通过把如下语句加入Nginx备份脚本配合,定时重启python程序,但能解决问题就OK了。

ps aux | grep monitoring.py | grep  -v "grep" | awk -F' ' '{print $2}' | xargs kill -9; python monitoring.py

'''

import re
import os
import sys
import time
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.header import Header


#匹配模式
pattern = r"(\[.*?\]).*?(10.10.101.[0-9][0-9]:8080)(ups_resp_time:.*)(request_time:.*)"
#日志路径
logfile='access.log'
#ip地址统计字典
result = {}
#当前日期时间
currntime = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))

#统计IP地址出现响应超时的次数
def counterror(ipaddr):
    if ipaddr not in result:
        result[ipaddr] = 0

result[ipaddr] += 1

return result

def analyzelog(lists):
    date = lists[0]
    ipaddr = lists[1]
    ups_resp_time = str(lists[2]).split(':')[1]
   
   
    #当前日期时间
    currntime = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))
    #print date,ipaddr+":"+ups_resp_time
    try:
    if float(ups_resp_time) > 10:
        counts = counterror(ipaddr)
        if counts[ipaddr] > 10:
            print ipaddr,"》》 错误次数 超过10!!《《 ",currntime
            msg = MIMEText('你好!! \n平台的 Nginx后端服务:'+ipaddr+",响应时间超过阈值(10ms),当前为:"+ups_resp_time+" 毫秒! \n 响应缓慢,请联系管理员检查!", 'plain', 'utf-8')
            msg['Subject'] = Header("Nginx后端服务响应告警!!", 'utf-8')
            sendMail(msg)
            counts[ipaddr] = 0
    except ValueError:
        print currntime,"值异常:",ups_resp_time
        #monitoring(logfile)
def sendMail(msg):

sender = 'linuxidc@linuxidc.com'
    receiver = ["linuxidc@163.com", "abc@163.com.cn"]
    smtpserver = 'smtp.linuxidc.com'
    user = 'linuxidc@linuxidc.com'
    passwd = 'linuxidc'
   
    #群发设置
    msg['To'] = ','.join(receiver)
   
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(user, passwd)
        smtp.sendmail(sender,receiver, msg.as_string())
        smtp.quit()
        print "OK"
    except:
        pass 85
def monitorlog(logfile):
    popen = subprocess.Popen('tail -f ' + logfile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    print "文件读取开始.... ",currntime
    pid = popen.pid
    print 'Popen.pid:' + str(pid)
   
    while True:
        line = popen.stdout.readline().strip()
        matchObj = re.findall(pattern, line, re.M)
       
        if line and len(matchObj) > 0:
            analyzelog(matchObj[0])
        else:
            continue

if __name__ == "__main__":
    print "Start"
    print "监控的日志文件是%s" % logfile
    monitorlog(logfile)

CentOS 7下Nginx服务器的安装配置 

CentOS上安装Nginx服务器实现虚拟主机和域名重定向 

CentOS 6.8 安装LNMP环境(Linux+Nginx+MySQL+PHP) 

Linux下安装PHP环境并配置Nginx支持php-fpm模块 

Nginx服务的SSL认证和htpasswd认证 

Linux中安装配置Nginx及参数详解 

Nginx日志过滤 使用ngx_log_if不记录特定日志

CentOS 7.2下Nginx+PHP+MySQL+Memcache缓存服务器安装配置 

CentOS6.9编译安装Nginx1.4.7 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/23895569889fe0e4d54a78917abb078c.html