es_host: 192.168.0.71 es_port: 9200 name: user_srv #规则名字必须是唯一的 type: frequency index: prod-yqh-srv.err.user_srv ## 监控的索引 num_events: 5 ## 限定时间内,发生的次数 timeframe: hours: 1 ## 一小时内有5个错误日志写进ES的话就发送邮件 filter: - regexp: ##以正则的方式匹配, “.*” 就是已有日志写进es就算 message: ".*" alert: - "dingtalk_alert.DingTalkAlerter" dingtalk_webhook: "https://oapi.dingtalk.com/robot/send?access_token=9cb8e9e5e830ce3576fb17439c7b1cd6d3438f3136831db4292f3158edcfd27b" dingtalk_msgtype: "text" dingtalk_atMobiles: ["15510721980"]
以上是user_srv.yml的内容
下面是dingtalk_alert.py的内容
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: xuyaoqiang
@contact: xuyaoqiang@gmail.com
@date: 2017-09-14 17:35
@version: 0.0.0
@license:
@copyright:
"""
import json
import requests
#from elastalert.alerts import Alerter, DateTimeEncoder
from alerts import Alerter, DateTimeEncoder
from requests.exceptions import RequestException
#from elastalert.util import EAException
from util import EAException
class DingTalkAlerter(Alerter):
required_options = frozenset(['dingtalk_webhook', 'dingtalk_msgtype','dingtalk_atMobiles'])
def __init__(self, rule):
super(DingTalkAlerter, self).__init__(rule)
self.dingtalk_webhook_url = self.rule['dingtalk_webhook']
self.dingtalk_msgtype = self.rule.get('dingtalk_msgtype', 'text')
self.dingtalk_isAtAll = self.rule.get('dingtalk_isAtAll', False)
self.dingtalk_atMobiles = self.rule['dingtalk_atMobiles']
self.digtalk_title = self.rule.get('dingtalk_title', '')
def format_body(self, body):
return body.encode('utf8')
def alert(self, matches):
headers = {
"Content-Type": "application/json",
"Accept": "application/json;charset=utf-8"
}
body = self.create_alert_body(matches)
atMobiles = self.dingtalk_atMobiles
payload = {
"msgtype": self.dingtalk_msgtype,
"text": {
"content": body
},
"at": {
"atMobiles": atMobiles,
"isAtAll":False
}
}
try:
response = requests.post(self.dingtalk_webhook_url,
data=json.dumps(payload, cls=DateTimeEncoder),
headers=headers)
response.raise_for_status()
except RequestException as e:
raise EAException("Error request to Dingtalk: {0}".format(str(e)))
def get_info(self):
return {
"type": "dingtalk",
"dingtalk_webhook": self.dingtalk_webhook_url
}
pass
if __name__=="__main__":
from elastalert.alerts import Alerter, DateTimeEncoder