在公司里做的一个接口系统,主要是对接第三方的系统接口,所以,这个系统里会和很多其他公司的项目交互。随之而来一个很蛋疼的问题,这么多公司的接口,不同公司接口的稳定性差别很大,访问量大的时候,有的不怎么行的接口就各种出错了。

这个接口系统刚刚开发不久,整个系统中,处于比较边缘的位置,不像其他项目,有日志库,还有短信告警,一旦出问题,很多情况下都是用户反馈回来,所以,我的想法是,拿起python,为这个项目写一个监控。如果在调用某个第三方接口的过程中,大量出错了,说明这个接口有有问题了,就可以更快的采取措施。

项目的也是有日志库的,所有的info,error日志都是每隔一分钟扫描入库,日志库是用的mysql,表里有几个特别重要的字段:

  • level 日志级别
  • message 日志内容
  • file_name Java代码文件
  • log_time 日志时间

有日志库,就不用自己去线上环境扫日志分析了,直接从日志库入手。由于日志库在线上时每隔1分钟扫,那我就去日志库每隔2分钟扫一次,如果扫到有一定数量的error日志就报警,如果只有一两条错误就可以无视了,也就是短时间爆发大量错误日志,就可以断定系统有问题了。报警方式就用发送邮件,所以,需要做下面几件事情:
1. 操作MySql。
2. 发送邮件。
3. 定时任务。
4. 日志。
5. 运行脚本。

明确了以上几件事情,就可以动手了。
操作数据库

使用MySQLdb这个驱动,直接操作数据库,主要就是查询操作。
获取数据库的连接:

1
2
3
4
5
6
7
8
def get_con():
 host = "127.0.0.1"
 port = 3306
 logsdb = "logsdb"
 user = "root"
 password = "never tell you"
 con = MySQLdb.connect(host=host, user=user, passwd=password, db=logsdb, port=port, charset="utf8")
 return con

从日志库里获取数据,获取当前时间之前2分钟的数据,首先,根据当前时间进行计算一下时间。之前,计算有问题,现在已经修改。

1
2
3
4
5
def calculate_time():
  
 now = time.mktime(datetime.now().timetuple())-60*2
 result = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
 return result

然后,根据时间和日志级别去日志库查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def get_data():
 select_time = calculate_time()
 logger.info("select time:"+select_time)
 sql = "select file_name,message from logsdb.app_logs_record " \
   "where log_time >"+"'"+select_time+"'" \
   "and level="+"'ERROR'" \
   "order by log_time desc"
 conn = get_con()
  
 cursor = conn.cursor()
 cursor.execute(sql)
 results = cursor.fetchall()
  
 cursor.close()
 conn.close()
  
 return results

发送邮件

使用python发送邮件比较简单,使用标准库smtplib就可以
这里使用163邮箱进行发送,你可以使用其他邮箱或者企业邮箱都行,不过host和port要设置正确。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def send_email(content):
  
sender = "sender_monitor@163.com"
receiver = ["rec01@163.com", "rec02@163.com"]
host = 'smtp.163.com'
port = 465
msg = MIMEText(content)
msg['From'] = "sender_monitor@163.com"
msg['To'] = "rec01@163.com,rec02@163.com"
msg['Subject'] = "system error warning"
  
try:
smtp = smtplib.SMTP_SSL(host, port)
smtp.login(sender, '123456')
smtp.sendmail(sender, receiver, msg.as_string())
logger.info("send email success")
except Exception, e:
logger.error(e)

定时任务

使用一个单独的线程,每2分钟扫描一次,如果ERROR级别的日志条数超过5条,就发邮件通知。

1
2
3
4
5
6
7
8
9
10
11
12
def task():
while True:
logger.info("monitor running")
  
results = get_data()
if results is not None and len(results) > 5:
content = "recharge error:"
logger.info("a lot of error,so send mail")
for r in results:
content += r[1]+'\n'
send_email(content)
sleep(2*60)

日志

为这个小小的脚本配置一下日志log.py,让日志可以输出到文件和控制台中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# coding=utf-8
import logging
  
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
  
fh = logging.FileHandler('monitor.log')
fh.setLevel(logging.INFO)
  
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
  
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
  
logger.addHandler(fh)
logger.addHandler(ch)

所以,最后,这个监控小程序就是这样的app_monitor.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# coding=utf-8
import threading
import MySQLdb
from datetime import datetime
import time
import smtplib
from email.mime.text import MIMEText
from log import logger
  
  
def get_con():
 host = "127.0.0.1"
 port = 3306
 logsdb = "logsdb"
 user = "root"
 password = "never tell you"
 con = MySQLdb.connect(host=host, user=user, passwd=password, db=logsdb, port=port, charset="utf8")
 return con
  
  
def calculate_time():
  
 now = time.mktime(datetime.now().timetuple())-60*2
 result = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
 return result
  
  
def get_data():
 select_time = calculate_time()
 logger.info("select time:"+select_time)
 sql = "select file_name,message from logsdb.app_logs_record " \
   "where log_time >"+"'"+select_time+"'" \
   "and level="+"'ERROR'" \
   "order by log_time desc"
 conn = get_con()
  
 cursor = conn.cursor()
 cursor.execute(sql)
 results = cursor.fetchall()
  
 cursor.close()
 conn.close()
  
 return results
  
  
def send_email(content):
  
 sender = "sender_monitor@163.com"
 receiver = ["rec01@163.com", "rec02@163.com"]
 host = 'smtp.163.com'
 port = 465
 msg = MIMEText(content)
 msg['From'] = "sender_monitor@163.com"
 msg['To'] = "rec01@163.com,rec02@163.com"
 msg['Subject'] = "system error warning"
  
 try:
  smtp = smtplib.SMTP_SSL(host, port)
  smtp.login(sender, '123456')
  smtp.sendmail(sender, receiver, msg.as_string())
  logger.info("send email success")
 except Exception, e:
  logger.error(e)
  
  
def task():
 while True:
  logger.info("monitor running")
  results = get_data()
  if results is not None and len(results) > 5:
   content = "recharge error:"
   logger.info("a lot of error,so send mail")
   for r in results:
    content += r[1]+'\n'
   send_email(content)
  time.sleep(2*60)
  
  
def run_monitor():
 monitor = threading.Thread(target=task)
 monitor.start()
  
  
if __name__ == "__main__":
 run_monitor()

运行脚本

脚本在服务器上运行,使用supervisor进行管理。
在服务器(centos6)上安装supervisor,然后在/etc/supervisor.conf中加入一下配置:

复制代码代码如下:
[program:app-monitor]
command = python /root/monitor/app_monitor.py
directory = /root/monitor
user = root

然后在终端中运行supervisord启动supervisor。
在终端中运行supervisorctl,进入shell,运行status查看脚本的运行状态。
总结

这个小监控思路很清晰,还可以继续修改,比如:监控特定的接口,发送短信通知等等。
因为有日志库,就少了去线上正式环境扫描日志的麻烦,所以,如果没有日志库,就要自己上线上环境扫描,在正式线上环境一定要小心哇~

使用Python实现一个简单的项目监控的更多相关文章

  1. 用Python编写一个简单的Http Server

    用Python编写一个简单的Http Server Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器.Python支持该功能的实现模块是BaseFTTPServe ...

  2. 用Python写一个简单的Web框架

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  3. 用IntelliJ IDEA学习Spring--创建一个简单的项目

    这段时间想学习一下Spring,其实之前学过Spring,只是有些忘记了.而且之前学的时候是适用eclipse学习的,现在好像对IntelliJ这个工具使用挺多的,现在就学习一下这个工具的用法,顺便复 ...

  4. 《maven实战》笔记(2)----一个简单maven项目的搭建,测试和打包

    参照<maven实战>在本地创建对应的基本项目helloworld,在本地完成后项目结构如下: 可以看到maven项目的骨架:src/main/java(javaz主代码)src/test ...

  5. python中一个简单的webserver

     python中一个简单的webserver 2013-02-24 15:37:49 分类: Python/Ruby 支持多线程的webserver   1 2 3 4 5 6 7 8 9 10 11 ...

  6. Python实现一个简单三层神经网络的搭建并测试

    python实现一个简单三层神经网络的搭建(有代码) 废话不多说了,直接步入正题,一个完整的神经网络一般由三层构成:输入层,隐藏层(可以有多层)和输出层.本文所构建的神经网络隐藏层只有一层.一个神经网 ...

  7. 基于Spring aop写的一个简单的耗时监控

    前言:毕业后应该有一两年没有好好的更新博客了,回头看看自己这一年,似乎少了太多的沉淀了.让自己做一个爱分享的人,好的知识点拿出来和大家一起分享,一起学习. 背景: 在做项目的时候,大家肯定都遇到对一些 ...

  8. python 搭建一个简单的 搜索引擎

    我把代码和爬好的数据放在了git上,欢迎大家来参考 https://github.com/linyi0604/linyiSearcher 我是在 manjaro linux下做的, 使用python3 ...

  9. python 写一个类似于top的监控脚本

    最近老板给提出一个需要,项目需求大致如下:      1.用树莓派作为网关,底层接多个ZigBee传感节点,网关把ZigBee传感节点采集到的信息通过串口接收汇总,并且发送给上层的HTTP Serve ...

随机推荐

  1. 什么是python 中的顶层代码?

    在python语言中我们经常会听到顶层代码的说法,但是什么是顶层代码? 在python中,我们是以缩进来区分代码层次的,所以顶层代码指的是缩进为0个空格的代码. 看如下例子: PP = 3.14 de ...

  2. jquery.placeholder.min.js让吃屎的IE浏览器支持placeholder去吧

    描述:现在都是HTML5时代了,所有的浏览器都支持placeholder,唯独IE不支持.现在我们有了这款插件,IE下终于可以支持了!  图片展示:   兼容浏览器:IE6+/Firefox/Goog ...

  3. uva1352 Colored Cubes LA3401

    白书第一章例题8 好麻烦! 正方体每面编号为0-5,那么根据顶点和正面,就能确定形态.一共6*4=24种形态. P[i]表示编号i所在位置.比如P[1]=3,表示第二面转到了第四面. 就可以表示出所有 ...

  4. linux下的基础操作

    Xfce 终端: Linux 命令行终端,打开后会进入 zsh Shell 环境,可以使用 Linux 命令. NetSurf 网络浏览器:浏览器,可以用在需要前端界面的课程里,只需要打开环境里写的 ...

  5. 部署 k8s Cluster(下)【转】

    上节我们通过 kubeadm 在 k8s-master 上部署了 Kubernetes,本节安装 Pod 网络并添加 k8s-node1 和 k8s-node2,完成集群部署. 安装 Pod 网络 要 ...

  6. django 数据库的一些操作

    1.数据过滤: 使用filter()方法 >>> Publisher.objects.filter(name='Apress') [<Publisher: Apress> ...

  7. PHP15 Smarty模板

    学习目标 Smarty基本概念 Smarty安装和配置 Smarty模板设计 Smarty流程控制 Smarty基本概念 一种模板引擎,在系统中进行预处理和过滤数据.是主流的PHP模板引擎,此外PHP ...

  8. [CF] 950B Intercepted Message

    B. Intercepted Message time limit per test1 second memory limit per test512 megabytes inputstandard ...

  9. SpringCloud版本介绍和SpringBoot的兼容性

    Spring Cloud是一个由众多独立子项目组成的大型综合项目,每个子项目有不同的发行节奏,都维护着自己的发布版本号.Spring Cloud通过一个资源清单BOM(Bill of Material ...

  10. centos7 rsync+inotify软件实现集群服务的数据备份(一)

    一.rsync软件的说明: 1.1 什么是rsync rsync是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件.它使用所谓的“Rsync演算法”来使本地和远程两个主机之间的文件达 ...