python-监控error日志,实时发送到钉钉

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/liyyzz33/article/details/84570994

原理用python常链接一个日志文件,每当有新的内容写入,就通过钉钉机器人转发到群里

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

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

serverip="服务器IP"
name="日志名"
timenow=datetime.datetime.now().strftime('%Y%m%d')
logname=name + timenow + ".log" #拼成的日志name

print logname

def http_post( errmsg ):

	url = "钉钉机器人链接"

        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

file = open('/Path/'+ logname)
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)

猜你喜欢

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