在自测过程中为了方便定位日志,于是想到将错误的日志监控通过钉钉群进行通知,这样既方便于快速定位问题,也方便于全天监控服务报错。话不多说下面是代码
考虑到大部分linux系统预装都是python2.7的环境,以下代码以及依赖都在python2.7基础之上运行
环境准备 服务器安装pip执行:wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
安装:python get-pip.py
pip install requests
pip install ConfigParser
# coding=utf-8
import base64
import hashlib
import hmac
import json
import time
import urllib
import requests
from ConfigParser import ConfigParser
def getProperties(first, second):
try:
conf = ConfigParser()
conf.read('./properties.conf')
name = conf.get(first, second)
except Exception as e:
raise e
return name
def sendMessage(lines):
timestamp = str(int(round(time.time() * 1000)))
secret = getProperties('dingtalk', 'secret')
accessToken = getProperties('dingtalk', 'accessToken')
secret_enc = secret.encode('utf-8')
string_to_sign = '{}n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.quote_plus(base64.b64encode(hmac_code))
url = accessToken + "×tamp=" + timestamp + "&sign=" + sign
headers = {'content-type': "application/json"}
body = {"msgtype": "text", "text": {"content": lines}}
r = requests.post(url, data=json.dumps(body), headers=headers)
print(r.text)
print(lines)
def getLog(filePathAppoint, filterStr):
with open(filePathAppoint, 'r+') as file_read:
while True:
flag = False
lines = file_read.readline()
if not lines:
# 读取到文件末尾行等待
isGoFileEnd = True
time.sleep(3)
# 首次启动等待读取到末尾
if not isGoFileEnd:
continue
for item in filterStr:
if lines.lower().__contains__(item.lower()):
flag = True
if flag:
sendMessage(lines)
if __name__ == '__main__':
filepath_appoint = getProperties('logfile', 'fileLocation')
strFilter = getProperties('logfile', 'filter').split(" | ")
getLog(filepath_appoint, strFilter)
重启脚本 restart.sh
#!/bin/bash
PID=`ps -ef|grep ErrorDingTalk.py | grep -v "grep" | awk '{print $2}' `
echo $PID
if [ -z $PID ]; then
echo "未启动服务"
else
kill -9 $PID
fi
# 判断传入的参数是否为stop 如果为stop只杀死进程不启动服务
if [ "$1" == "stop" ];then
echo "进程已杀死"
else
nohup python ErrorDingTalk.py &
echo "启动服务成功"
fi
新建脚本配置文件properties.conf
[dingtalk] secret=SECa072d82a14e71bd5e766081e192170943c51a2e6b33182f5d381ff6c075a2a6a accessToken=https://oapi.dingtalk.com/robot/send?access_token=df8f30d07e73f9db3be803f29747f0ec710bdf3d19bf66f51bc77e70a6242f5f [logfile] # 日志文件地址 fileLocation=/var/log/uusafe/mbs/iosservice/server.log # 拦截关键词(不区分大小写) filter=error | exception使用 钉钉群配置
1、创建一个钉钉群,在群设置中选择智能群助手
2、选择添加自定义机器人
3、填写信息,选择加签
** 此处产生的加签信息要复制下来,填写到properties.conf的** secret 标签下 **
4、点击完成
** 此处会生成一个webhook地址,这个地址需要复制下来,填写到properties.conf的 accessToken **标签下 **
1、secret与accessToken在钉钉群配置已经介绍过
2、fileLocation
此处是要监控的日志文件
3、filter
此处是配置监控的关键词,多个关键词使用 空格|空格( | ) 进行分隔,此处不区分大小写,且关键词是或的关系
至此你就可以在钉钉上查看自己的日志了
参考
钉钉机器人消息推送:https://open.dingtalk.com/document/robots/robot-overview



