崩溃数据暴涨实时报警功能实现

corntab命令 + python脚本

某些崩溃统计平台没有提供实时报警功能,或者我们需要定制报警策略,这时候我们可以抓取页面接口,自己实现报警

crontab命令执行定时任务
crontab使用详解

原理是每分钟抓取一次崩溃数据,大于阈值报警(策略自己定)
能够满足崩溃实时报警功能,通过短信和im工具报警,避免延误最佳修复时机

首先观察页面请求header中参数,分析后用python模拟浏览器登录,请求解析

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

import urllib2  
import urllib,httplib
import threading
import json
import time
import os
import sys

ISOTIMEFORMAT='%Y-%m-%d %H:%M:%S'
OUTFORMAT='%Y-%m-%d:%H:%M:%S'
product = ''
product_url_prefix = ''
cookie = ''
xtoken = ''
mails = ''
phones = ''
max = 0;


#def shadle():
#       print time.time()
#       getCrashData(product, product_url_prefix, cookie, xtoken, mails, phones, max)
#       threading.Timer(60,shadle).start()


def getCrashData(__product, __product_url_prefix, __cookie, __xtoken, emails, phonenumbers, maxline):
    product = __product
    product_url_prefix = __product_url_prefix
    cookie = __cookie
    xtoken = __xtoken
    mails = emails
    phones = phonenumbers
    max = maxline

    curTime = long(time.time())
    startTime = long(time.time() - 3600)
#    print time.strftime(ISOTIMEFORMAT,time.localtime(startTime)), time.strftime(ISOTIMEFORMAT, time.localtime(curTime))

    req = urllib2.Request(__product_url_prefix + '&start=%s&end=%s' %(startTime, curTime))
    req.add_header('Cookie', __cookie)
    req.add_header('X-CRASHLYTICS-DEVELOPER-TOKEN', __xtoken)

    content = ''
    try:
        resp = urllib2.urlopen(req)
        content = resp.read()

    except urllib2.HTTPError,e:    #HTTPError必须排在URLError的前面
        print "The server couldn't fulfill the request"
        print "Error code:",e.code
        print "Return content:",e.read()
        shadle()
        return
    except urllib2.URLError,e:
        print "Failed to reach the server"
        print "The reason:",e.reason
        shadle()
        return

#    print content

    js = json.loads(content)

#    with open(__product + '_pid.txt','w') as f:
#        f.write(bytes(os.getpid()))

    fivec = 0
    for a in js['series'][-5:]:
        fivec += a[1]


    str = __product + time.strftime(OUTFORMAT,time.localtime(js['series'][-1][0])) + '当前分钟崩溃数:' + bytes(js['series'][-3][1]) + "最近五分钟崩溃平均值:" + bytes(float(fivec)/5)

    if time.localtime(time.time()).tm_min == 0:
        r = urllib2.Request('im工具报警url')
        urllib2.urlopen(r)

#    r = urllib2.Request('im工具报警url')
#    urllib2.urlopen(r)

    if js['series'][-3][1] >= maxline:
#        print js['series'][-3][1]
        r = urllib2.Request('im工具报警url')
        urllib2.urlopen(r)
        for p in phonenumbers:
            r = urllib2.Request('短信报警接口url')
            urllib2.urlopen(r)

    sys.exit()
            

你可能感兴趣的:(崩溃数据暴涨实时报警功能实现)