#!/usr/bin/python
#-*- coding: utf-8 -*
import urllib, json, requests
import sys, shutil, os, string, datetime,time
serverip="99"
name="slow.log"
msg = [] #定义一个空列表将while循环中每次读出的行作为一个元素接收
def msg_format(data):
global msg
if data.startswith("#") or data.startswith("SET"):
msg = []
if "User@Host" in data: #过滤出库信息并分割字符
uh = data.split("@")
host = uh[1]
http_post(host)
else:
msg.append(data)
if data.endswith(";"):
strmsg = ' '.join(msg)
http_post(strmsg)
def http_post(errmsg):
url = "https://oapi.dingtalk.com/robot/send?access_token=xxxx"
values = {"msgtype": "text"}
content = {}
content["content"] = serverip + "slow_sql_msg:" + errmsg
values["text"] = content
headers = {"Content-Type":"application/json;charset=UTF-8"}
jdata = json.dumps(values)
req = requests.post(url=url, headers=headers, data=jdata)
print(req.content.decode())
file = open('/usr/local/mysql/logs/'+ name)
file.seek(0, os.SEEK_END)
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
msg_format(line[:-1]) #删除每行的最后一个字符(即换行符)