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

这个接口系统刚刚开发不久,整个系统中,处于比较边缘的位置,不像其他项目,有日志库,还有短信告警,一旦出问题,很多情况下都是用户反馈回来,所以,我的想法是,拿起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. .NET多线程总结

    1.不需要传递参数,也不需要返回参数 我们知道启动一个线程最直观的办法是使用Thread类,具体步骤如下: public void test() { ThreadStart threadStart = ...

  2. python基础一 day5 知识点

    Unicode转化为gbk和utf-8 表现形式:str转化为bytes

  3. Java数据结构和算法(三)--三大排序--冒泡、选择、插入排序

    三大排序在我们刚开始学习编程的时候就接触过,也是刚开始工作笔试会遇到的,后续也会学习希尔.快速排序,这里顺便复习一下 冒泡排序: 步骤: 1.从首位开始,比较首位和右边的索引 2.如果当前位置比右边的 ...

  4. Vue之过滤器的使用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. windows cmd 模仿电影黑客

    1.win+R 2.输入cmd 3.按F11进入全屏 4.color a 改变颜色为绿色(可能看起来秀一点) 5.dir/s 查看所有文件,就跑起来了,看起来很酷,但是在懂得人眼里,没什么的(所以只能 ...

  6. Centos7 安装 MySQL8以及远程访问的配置

    Centos7 安装MySQL8 1. 添加MySQL8的本地源 执行以下命令获取安装MySQL源 [root@virde ~]# wget https://repo.mysql.com//mysql ...

  7. Go:json(序列化、反序列化)

    一.示例 package main import ( "encoding/json" "fmt" ) type Person struct { Name str ...

  8. Ubuntu中python链接本地数据库

    由于python链接数据库需要下载DB API模块:例如你需要访问Mysql数据,你需要MySQL数据库模块. DB-API是一个规范. 以便为不同的底层数据库系统和数据库接口程序提供一致的访问接口. ...

  9. 如何将已经安装从chrome扩展程序导出备份为.CRX文件?

    之前介绍过CRX Extractor可以从chrome应用商店下载备份扩展程序,有读者朋友问说:如果 Google Chrome扩展程序已经从 Chrome应用商店下架,还有没有方法下载呢?通常网路上 ...

  10. C#基于引用创建单链表

    在C语言,单链表的实现依赖指针,指针用来指向节点,那么,用C#实现,自然就想到引用,节点的引用不就类似于指向Node的指针嘛