晋级版python3的:https://blog.csdn.net/liyyzz33/article/details/97789920
这个比较老了也可参考

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

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

以下是error.py内容

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

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

filelog = sys.argv[1]
serverip = sys.argv[2] #来标识是那个服务器发送的警报


def http_post( errmsg ):

	url = "https://oapi.dingtalk.com/robot/send?access_token=174ac61f8dc49cf49e039576223d09f29b344e6ae21cfc837534ed7de6a9249d"

        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

def senderror( filepath ):
        file = open(filepath)
        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)


senderror( filelog )


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

#!/bin/bash

comm=$1
serverip=`curl http://metadata.tencentyun.com/meta-data/public-ipv4`
date=`date +%Y%m%d`
pro1='/data/logs/dalu/dalu1'$date.log
pro2='/data/logs/dalu/dalu2'$date.log
pro3='/data/logs/php-fpm/www-error.log'


echo $comm

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/alarm/php_error.py $1 $serverip &
	
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is starting" >> /data/logs/python.log

	sleep 5
		
	CurrentPystatus=`ps -ef | grep $1 | grep -v grep | wc -l`
	
	if [ $CurrentPystatus -ne 0 ];
	then
	echo "`date "+%Y-%m-%d %H:%M:%S"`:$1 is running" >> /data/logs/python.log	
	fi
fi
}

if [ "$comm" = "start" ];then

	cd /data/logs

	for error in $pro{1..3}

	do	

		start $error 

	done
elif [ "$comm" = "stop" ];then

ps -ef|grep /root/dalu/alarm/php_error.py |grep -v grep|cut -c 9-15|xargs kill -9

else
	echo "输入有误,请带参数stop or start!"
	
fi
echo 1

自动任务
##钉钉告警
1 0 * * * /root/dalu/alarm/alarmd.sh stop > /dev/null 2>&1 & #明天终止昨天的日志
*/1 * * * * /root/dalu/alarm/alarmd.sh start > /dev/null 2>&1 & #检查有没有新的错误日志并启动监控脚本

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐