使用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 ...
随机推荐
- feign 负载均衡熔断器
feign:和zuul配合进行负载均衡. 注解的含义: @EnableDiscoveryClient 声明它是一个资源服务端,即可以通过某些接口调用一些资源: @EnableFeignClients ...
- uva1611 Crane
类似煎饼,先把1放到1,之后是子问题 (先放到前一半,再放到开头,两次操作)(任何位置,最多一次就可以放到前一半)) #include<iostream> #include<ve ...
- python基础一day4 元组
结果: join:返回一个字符串 列表转化为字符串 可迭代对象都可以 结果: 不报错什么也不执行 结果:
- pooling需要注意的一个地方
max pooling 在不同的 depth 上是分开执行的,且不需要参数控制.也就是说,pooling之后,feature map的维度不会改变
- 二叉排序树BST
注意:对一个二叉排序树进行中序遍历时,得到的序列是一个按值从小到大排列的有序序列 查找性能的分析:
- 框模型中设置内容区域元素占地尺寸box-sizing属性
盒子模型有两种 一种是 内容盒子模型(content-box)一种是边框盒子模型(border-box). content-box:设置的尺寸,只设置内容区域, 左外边距+左边框+左内边距+内容区域宽 ...
- Swift 中的Range和NSRange不同
Swift中的Ranges和Objective-C中的NSRange有很大的不同,我发现在处理Swift中Ranges相关的问题的时候,总是要花费比我想象的更多的时间.不过,现在回过头来看看,发现Sw ...
- Python爬虫-Scrapy-CrawlSpider与ItemLoader
一.CrawlSpider 根据官方文档可以了解到, 虽然对于特定的网页来说不一定是最好的选择, 但是 CrwalSpider 是爬取规整的网页时最常用的 spider, 而且有很好的可塑性. 除了继 ...
- POJ 1655 Balancing Act (树形DP求树的重心)
题意: 求一棵树中以某个点为重心最小的子树集, 就是去掉这个点, 图中节点最多的联通块节点最少. 分析: 想知道这个点是不是最优的点, 只要比较它子树的数量和除去这部分其他的数量(它的父节点那部分树) ...
- ubuntu修改apt-get源为国内镜像源
1.原文件备份 sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak 2.编辑源列表文件 sudo vim /etc/apt/so ...