使用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 ...
随机推荐
- python基础一 day2 字符串操作
s.capitalize() s.upper() s.lower() s.swapcase() s.title() s.center(20,"#") s.expand ...
- render_to_response()
render_to_response('模板名称',字典) 字典:第二个参数必须是为该模板创建context时所使用的字典,如果不提供第二个参数,render_response()使用一个空字典
- ES6 第一章 let和const命令 具体参照http://es6.ruanyifeng.com
1.let类似于var用用来定义变量 1)let没有预解析,不存在变量提升 // var 的情况 console.log(foo); // 输出undefined var foo = 2; // le ...
- Spring-1-IOC
IOC与DI的区别? IOC:控制反转(Inversion of Control是面向对象的一种设计原则,可以用来降低计算机之间的耦合度,其中最常见的是依赖注入).是实现的目标 DI:是实现IOC的一 ...
- java使用数据库连接池
连接池的实现方式是首先使用JNDI(JavaTM Naming and Directory Interface) 将数据源对象注册为一个命名服务,然后使用JNDI提供的服务接口,按照名称检索对应的数据 ...
- zabbix auto discovery
1.configuration>discovery>create discovery rule ip range:192.168.43.2-254 check: http 80 2.con ...
- Xcode导入第三方库
Xcode导入第三方库,例如TapkuLibrary iOS开源框架Tapku下载地址:https://github.com/devinross/tapkulibrary.git 1.创建你的工程项目 ...
- POJ-3278 抓住这头牛
广搜解决. 广搜搜出最短路,直接输出返回就行了. 每个点只搜一次,而且界限进行一次判断. else 语句里面不要用if else if,这样的话就直走一条路了. #include <ios ...
- <Spring Data JPA>二 Spring Data Jpa
1.pom依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...
- 【笔记】linux x86漏洞利用
0x1任意代码执行是如何实现的? 任意代码执行使用一种叫“覆盖返回地址”的技术来实现.这种方式使得攻击者重写位于栈上的返回地址,这将导致任意代码执行.