python——nagios监控nginx日志 request_time

遇到问题:nginx日志包含非常重要的信息。比如upstream_response_time 和request_time。现需求监控改值。

解决问题:编写python脚本,通过nagios check_nrpe 插件完成监控。


前提了解: nginx日志格式:

log_format  main  '$remote_addr |$time_local| $request | $status | $body_byte

s_sent | $http_referer | $http_user_agent | $upstream_response_time | $request_t

ime | $upstream_addr';


日志范例:

10.113.205.117 |13/Sep/2016:21:24:07 +0800| POST /test/test HTTP/1.0 | 200 | 223 | - | Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) | 0.034 | 0.042 | 10.156.168.193:8001


通过观察nginx日志范例,于是有了监控脚本的思路。 监控日志的最后输出一行,将倒数第二列和倒数第三列拎出来做值的比较大小。值大于10s,则表示该站点响应较慢,应及时报警。 nagios会对脚本执行返回的状态码有一个反馈。返回0,nagios 显示ok;返回2,nagios显示critial,并触发报警。


nagios客户端操作:

nagios客户端添加脚本,python脚本如下:


#!/usr/bin/python

# -*- coding:UTF-8 -*-


import subprocess

import os

import sys


api = ("tail -n 1 /mnt/log/nginx/test.test.cn.log")


def testtime():

    child= subprocess.Popen(api,shell=True,stdout=subprocess.PIPE)

    line = child.stdout.readline()

    upstream_response_time = float(line.split("|")[-3].strip())

    request_time = float(line.split("|")[-2].strip())

    line = line.replace('|','')


    if upstream_response_time < 10 or request_time < 10 :

        print "OK - api.test.cn request time ok"

        sys.exit(0)

    else:

        print "CRITIAL- api.test.cn %s %s " % (upstream_response_time ,request_time),"Link is: ",line,

        sys.exit(2)


if __name__ == '__main__':

    testtime()


将该脚本添加到 插件目录下,并给执行权限。

[root@nginx101 mcSitesConf]# ll /usr/local/nagios/libexec/check_requestime_test.py 

-rwxr-xr-x 1 root root 716 Sep 13 14:03 /usr/local/nagios/libexec/check_requestime_test.py

[root@nginx101 mcSitesConf]# 


nrpe 配置文件添加监控命令:

command[check_requestime_test]=/usr/local/nagios/libexec/check_requestime_test.py


添加完成,重启客户端的nrpe

ps aux | grep nrpe 

杀死进程id

启动如下:

/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d


至此,nagios客户端添加完成。可在服务端验证是否成功


nagios服务端操作:

[root@monitor101 ~]# /usr/lib64/nagios/plugins/check_nrpe -H 10.134.6.129 -c check_requestime_test

OK - api.test.cn request time ok


验证成功,开始添加监控服务文件

/etc/nagios/conf.d/services/nginx101.cfg 添加以下内容

define service{

        hostgroup_name          nginx.linux

        service_description     check_requestime_test status

        use                     system-level-service

        check_command           check_nrpe!check_requestime_test

        }


检查nagios配置文件是否正确,并重启nagios

service nagios checkconfig

service nagios reload


wKioL1fYAvPz1eJxAAC8JrhgeXo138.png-wh_50


注:以上涉及到某些自认为私密的链接和ip稍作修改,代码和监控方法正确,供参考。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值