標籤: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()
將該指令碼添加到 外掛程式目錄下,並給執行許可權。
[[email protected] 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
[[email protected] 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服務端操作:
[[email protected] ~]# /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
650) this.width=650;" src="http://s1.51cto.com/wyfs02/M00/87/38/wKioL1fYAvPz1eJxAAC8JrhgeXo138.png-wh_500x0-wm_3-wmp_4-s_1819898761.png" title="1.png" alt="wKioL1fYAvPz1eJxAAC8JrhgeXo138.png-wh_50" />
註:以上涉及到某些自認為私密的連結和ip稍作修改,代碼和監控方法正確,供參考。
本文出自 “濛sir的積累” 部落格,請務必保留此出處http://mengsir.blog.51cto.com/2992083/1852450
python——nagios監控nginx日誌 request_time