python-监控error错误日志,实时发送到钉钉(版本2)

版权声明:使用中有任何问题,可以留言。能解答尽量解答。 https://blog.csdn.net/liyyzz33/article/details/86610729

这一版是写了个方法,把要监控的日志当成变量传一下 就开启监控日志内容了。实现实时警报。

运行
nohup python /root/error.py 日志路径 &

以下是error.py内容

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

import urllib
import urllib2
import json
import sys, shutil, os, string, datetime,time

filelog = sys.argv[1]

errmsg = ""
serverip = "192.168.1.123" 
date = time.strftime("%Y%m%d",time.localtime())

def http_post( errmsg ):

	url = "https://oapi.dingtalk.com/这里是钉钉机器人链接"
	values = {'msgtype': 'text'}


        content = {}

        content['content'] = serverip + errmsg

        values['text'] = content

        headers = {'Content-Type':'application/json;charset=UTF-8'}

        jdata = json.dumps(values)

        print jdata

        req = urllib2.Request(url, jdata , headers)
        response = urllib2.urlopen(req)
        data = json.loads(response.read())
        errcode = data['errcode']
        print errcode
        return errcode

isNewFile = 0

while 1:
        isExists = os.path.exists(filelog)
        if not isExists:
                time.sleep(1)
                isNewFile = 1
        else:
                break


file = open(filelog)
if isNewFile == 0:
        file.seek(0, os.SEEK_END)
while 1:
        where = file.tell()
        line = file.readline()
        if not line:
                time.sleep(1)
                file.seek(where)
        else:
                print line,
                http_post(line)

下面用脚本定时检查是否新产生的错误日志,后自动用上面的py监控起。
注:日志文件有一定规律,规律自己把握

#!/bin/bash

date=`date +%Y%m%d`

dirpath='/data/logs/test_error'

function start () {
	
	Pystatus = 'ps -ef | grep $1 | grep -v grep | wc -l'

	if [ $pystatus -eq 0 ];
	
	then
	
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is not running" >> /data/logs/python.log    
	
	nohup python /root/dalu/error.py $1 &
	
	sleep 5
	
	CurrentPystatus = 'ps -ef | grep $1 | grep -v grep | wc -l'
	
	if [ $CurrentPythonPid -ne 0 ];
    then
    echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is running" >> /data/logs/python.log	

	fi

}

cd /data/logs

for error in `find $dirpath -name *test_error$date.log`

do	

	start $error 

done

猜你喜欢

转载自blog.csdn.net/liyyzz33/article/details/86610729