使用Python實現(xiàn)一個簡單的項目監(jiān)控
在公司里做的一個接口系統(tǒng),主要是對接第三方的系統(tǒng)接口,所以,這個系統(tǒng)里會和很多其他公司的項目交互。隨之而來一個很蛋疼的問題,這么多公司的接口,不同公司接口的穩(wěn)定性差別很大,訪問量大的時候,有的不怎么行的接口就各種出錯了。
這個接口系統(tǒng)剛剛開發(fā)不久,整個系統(tǒng)中,處于比較邊緣的位置,不像其他項目,有日志庫,還有短信告警,一旦出問題,很多情況下都是用戶反饋回來,所以,我的想法是,拿起python,為這個項目寫一個監(jiān)控。如果在調(diào)用某個第三方接口的過程中,大量出錯了,說明這個接口有有問題了,就可以更快的采取措施。
項目的也是有日志庫的,所有的info,error日志都是每隔一分鐘掃描入庫,日志庫是用的mysql,表里有幾個特別重要的字段:
- level 日志級別
- message 日志內(nèi)容
- file_name Java代碼文件
- log_time 日志時間
有日志庫,就不用自己去線上環(huán)境掃日志分析了,直接從日志庫入手。由于日志庫在線上時每隔1分鐘掃,那我就去日志庫每隔2分鐘掃一次,如果掃到有一定數(shù)量的error日志就報警,如果只有一兩條錯誤就可以無視了,也就是短時間爆發(fā)大量錯誤日志,就可以斷定系統(tǒng)有問題了。報警方式就用發(fā)送郵件,所以,需要做下面幾件事情:
1. 操作MySql。
2. 發(fā)送郵件。
3. 定時任務。
4. 日志。
5. 運行腳本。
明確了以上幾件事情,就可以動手了。
操作數(shù)據(jù)庫
使用MySQLdb這個驅(qū)動,直接操作數(shù)據(jù)庫,主要就是查詢操作。
獲取數(shù)據(jù)庫的連接:
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
從日志庫里獲取數(shù)據(jù),獲取當前時間之前2分鐘的數(shù)據(jù),首先,根據(jù)當前時間進行計算一下時間。之前,計算有問題,現(xiàn)在已經(jīng)修改。
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
然后,根據(jù)時間和日志級別去日志庫查詢數(shù)據(jù)
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
發(fā)送郵件
使用python發(fā)送郵件比較簡單,使用標準庫smtplib就可以
這里使用163郵箱進行發(fā)送,你可以使用其他郵箱或者企業(yè)郵箱都行,不過host和port要設置正確。
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級別的日志條數(shù)超過5條,就發(fā)郵件通知。
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,讓日志可以輸出到文件和控制臺中。
# 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)
所以,最后,這個監(jiān)控小程序就是這樣的app_monitor.py
# 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中加入一下配置:
command = python /root/monitor/app_monitor.py
directory = /root/monitor
user = root
然后在終端中運行supervisord啟動supervisor。
在終端中運行supervisorctl,進入shell,運行status查看腳本的運行狀態(tài)。
總結(jié)
這個小監(jiān)控思路很清晰,還可以繼續(xù)修改,比如:監(jiān)控特定的接口,發(fā)送短信通知等等。
因為有日志庫,就少了去線上正式環(huán)境掃描日志的麻煩,所以,如果沒有日志庫,就要自己上線上環(huán)境掃描,在正式線上環(huán)境一定要小心哇~
- 手動實現(xiàn)把python項目發(fā)布為exe可執(zhí)行程序過程分享
- python的即時標記項目練習筆記
- python調(diào)用新浪微博API項目實踐
- Python自動化運維和部署項目工具Fabric使用實例
- 對Python的Django框架中的項目進行單元測試的方法
- Linux下將Python的Django項目部署到Apache服務器
- 詳解使用Nginx和uWSGI配置Python的web項目的方法
- 把項目從Python2.x移植到Python3.x的經(jīng)驗總結(jié)
- Python中SOAP項目的介紹及其在web開發(fā)中的應用
- 十個Python練手的實戰(zhàn)項目,學會這些Python就基本沒問題了(推薦)
相關文章
python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼
這篇文章主要介紹了python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06一個基于flask的web應用誕生 bootstrap框架美化(3)
一個基于flask的web應用誕生第三篇,這篇文章主要介紹了前端框架bootstrap與flask框架進行整合,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04Python super( )函數(shù)用法總結(jié)
今天給大家?guī)淼闹R是關于Python的相關知識,文章圍繞著super( )函數(shù)展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06