python——nagios監控nginx日誌 request_time

遇到問題:nginx日誌包含很是重要的信息。好比upstream_response_time 和request_time。現需求監控改值。python

解決問題:編寫python腳本,經過nagios check_nrpe 插件完成監控。linux


前提了解: nginx日誌格式:ios

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

s_sent | $http_referer | $http_user_agent | $upstream_response_time | $request_tshell

ime | $upstream_addr';api


日誌範例:ide

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:8001spa


經過觀察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稍做修改,代碼和監控方法正確,供參考。

相關文章
相關標籤/搜索