使用Python实现一个简单的项目监控
在公司里做的一个接口系统,主要是对接第三方的系统接口,所以,这个系统里会和很多其他公司的项目交互。随之而来一个很蛋疼的问题,这么多公司的接口,不同公司接口的稳定性差别很大,访问量大的时候,有的不怎么行的接口就各种出错了。
这个接口系统刚刚开发不久,整个系统中,处于比较边缘的位置,不像其他项目,有日志库,还有短信告警,一旦出问题,很多情况下都是用户反馈回来,所以,我的想法是,拿起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 = 465msg = 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-8import 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-8import threadingimport MySQLdbfrom datetime import datetimeimport timeimport smtplibfrom email.mime.text import MIMETextfrom 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中加入一下配置:
command = python /root/monitor/app_monitor.py
directory = /root/monitor
user = root
然后在终端中运行supervisord启动supervisor。
在终端中运行supervisorctl,进入shell,运行status查看脚本的运行状态。
总结
这个小监控思路很清晰,还可以继续修改,比如:监控特定的接口,发送短信通知等等。
因为有日志库,就少了去线上正式环境扫描日志的麻烦,所以,如果没有日志库,就要自己上线上环境扫描,在正式线上环境一定要小心哇~
使用Python实现一个简单的项目监控的更多相关文章
- 用Python编写一个简单的Http Server
用Python编写一个简单的Http Server Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器.Python支持该功能的实现模块是BaseFTTPServe ...
- 用Python写一个简单的Web框架
一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...
- 用IntelliJ IDEA学习Spring--创建一个简单的项目
这段时间想学习一下Spring,其实之前学过Spring,只是有些忘记了.而且之前学的时候是适用eclipse学习的,现在好像对IntelliJ这个工具使用挺多的,现在就学习一下这个工具的用法,顺便复 ...
- 《maven实战》笔记(2)----一个简单maven项目的搭建,测试和打包
参照<maven实战>在本地创建对应的基本项目helloworld,在本地完成后项目结构如下: 可以看到maven项目的骨架:src/main/java(javaz主代码)src/test ...
- python中一个简单的webserver
python中一个简单的webserver 2013-02-24 15:37:49 分类: Python/Ruby 支持多线程的webserver 1 2 3 4 5 6 7 8 9 10 11 ...
- Python实现一个简单三层神经网络的搭建并测试
python实现一个简单三层神经网络的搭建(有代码) 废话不多说了,直接步入正题,一个完整的神经网络一般由三层构成:输入层,隐藏层(可以有多层)和输出层.本文所构建的神经网络隐藏层只有一层.一个神经网 ...
- 基于Spring aop写的一个简单的耗时监控
前言:毕业后应该有一两年没有好好的更新博客了,回头看看自己这一年,似乎少了太多的沉淀了.让自己做一个爱分享的人,好的知识点拿出来和大家一起分享,一起学习. 背景: 在做项目的时候,大家肯定都遇到对一些 ...
- python 搭建一个简单的 搜索引擎
我把代码和爬好的数据放在了git上,欢迎大家来参考 https://github.com/linyi0604/linyiSearcher 我是在 manjaro linux下做的, 使用python3 ...
- python 写一个类似于top的监控脚本
最近老板给提出一个需要,项目需求大致如下: 1.用树莓派作为网关,底层接多个ZigBee传感节点,网关把ZigBee传感节点采集到的信息通过串口接收汇总,并且发送给上层的HTTP Serve ...
随机推荐
- python3 进程与线程
1.进程定义 狭义的定义: 进程是正在运行的程序的实例. 广义的定义:进程是一个具有 一定独立功能的程序关于某个数据集合的一次运行活动.它可以申请和拥有系统资源,是一个动态的概念,是一个活动的实体.它 ...
- exportfs - 管理NFS共享文件系统列表
概述 (SYNOPSIS) /usr/sbin/exportfs [-avi] [-o options,..] [client:/path ..] /usr/sbin/exportfs -r [-v] ...
- ES6(vue)对象词法扩展
ES6 允许声明在对象字面量时使用简写语法,来初始化属性变量和函数的定义方法,并且允许在对象属性中进行计算操作: function getCar(make, model, value) { retur ...
- python小随笔
关于pip安装 .\pip.exe install --ignore-installed --upgrade tensorflow-gpu python可视化库 Seaborn:是一个基于matplo ...
- myBatis的binding错误:Invalid bound statement (not found)
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)错误这个问题我找了好久,终于找到了正确的写 ...
- Vue之组件的生命周期
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 《BUG创造队》作业8:软件测试与Alpha冲刺(第四天)
项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 BUG创造队 作业学习目标 (1)掌握软件测试基础技术.(2)学习 ...
- c++内联函数解析(inline)
一.基本定义 inline是C++语言中的一个关键字,可以用于程序中定义内联函数,inline的引进使内联函数的定义更加简单.说到内联函数,这里给出比较常见的定义,内联函数是C++中的一种特殊函数,它 ...
- POJ-2442-Sequence(二叉堆)
POJ-2442 Description Given m sequences, each contains n non-negative integer. Now we may select one ...
- KVM中存储的配置
存储配置和启动顺序 QEMU提供了对多种块存储设备的模拟,包括IDE设备.SCSI设备.软盘.U盘.virtio磁盘等,而且对设备的启动顺序提供了灵活的配置. 1. 存储的基本配置选项 在qemu-k ...