亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用Python實(shí)現(xiàn)一個(gè)簡單的項(xiàng)目監(jiān)控

 更新時(shí)間:2015年03月31日 16:27:31   作者:Defshine  
這篇文章主要介紹了使用Python實(shí)現(xiàn)一個(gè)簡單的項(xiàng)目監(jiān)控,包括連接數(shù)據(jù)庫進(jìn)行查詢等操作,需要的朋友可以參考下

在公司里做的一個(gè)接口系統(tǒng),主要是對接第三方的系統(tǒng)接口,所以,這個(gè)系統(tǒng)里會和很多其他公司的項(xiàng)目交互。隨之而來一個(gè)很蛋疼的問題,這么多公司的接口,不同公司接口的穩(wěn)定性差別很大,訪問量大的時(shí)候,有的不怎么行的接口就各種出錯(cuò)了。

這個(gè)接口系統(tǒng)剛剛開發(fā)不久,整個(gè)系統(tǒng)中,處于比較邊緣的位置,不像其他項(xiàng)目,有日志庫,還有短信告警,一旦出問題,很多情況下都是用戶反饋回來,所以,我的想法是,拿起python,為這個(gè)項(xiàng)目寫一個(gè)監(jiān)控。如果在調(diào)用某個(gè)第三方接口的過程中,大量出錯(cuò)了,說明這個(gè)接口有有問題了,就可以更快的采取措施。

項(xiàng)目的也是有日志庫的,所有的info,error日志都是每隔一分鐘掃描入庫,日志庫是用的mysql,表里有幾個(gè)特別重要的字段:

  •         level 日志級別
  •         message 日志內(nèi)容
  •         file_name Java代碼文件
  •         log_time 日志時(shí)間

有日志庫,就不用自己去線上環(huán)境掃日志分析了,直接從日志庫入手。由于日志庫在線上時(shí)每隔1分鐘掃,那我就去日志庫每隔2分鐘掃一次,如果掃到有一定數(shù)量的error日志就報(bào)警,如果只有一兩條錯(cuò)誤就可以無視了,也就是短時(shí)間爆發(fā)大量錯(cuò)誤日志,就可以斷定系統(tǒng)有問題了。報(bào)警方式就用發(fā)送郵件,所以,需要做下面幾件事情:
1. 操作MySql。
2. 發(fā)送郵件。
3. 定時(shí)任務(wù)。
4. 日志。
5. 運(yùn)行腳本。

明確了以上幾件事情,就可以動手了。
操作數(shù)據(jù)庫

使用MySQLdb這個(gè)驅(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ù),獲取當(dāng)前時(shí)間之前2分鐘的數(shù)據(jù),首先,根據(jù)當(dāng)前時(shí)間進(jìn)行計(jì)算一下時(shí)間。之前,計(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í)間和日志級別去日志庫查詢數(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ā)送郵件比較簡單,使用標(biāo)準(zhǔn)庫smtplib就可以
這里使用163郵箱進(jìn)行發(fā)送,你可以使用其他郵箱或者企業(yè)郵箱都行,不過host和port要設(shè)置正確。
 

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)

定時(shí)任務(wù)

使用一個(gè)單獨(dú)的線程,每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)

日志

為這個(gè)小小的腳本配置一下日志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)

所以,最后,這個(gè)監(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()

運(yùn)行腳本

腳本在服務(wù)器上運(yùn)行,使用supervisor進(jìn)行管理。
在服務(wù)器(centos6)上安裝supervisor,然后在/etc/supervisor.conf中加入一下配置:

復(fù)制代碼 代碼如下:
[program:app-monitor]
command = python /root/monitor/app_monitor.py
directory = /root/monitor
user = root

然后在終端中運(yùn)行supervisord啟動supervisor。
在終端中運(yùn)行supervisorctl,進(jìn)入shell,運(yùn)行status查看腳本的運(yùn)行狀態(tài)。
總結(jié)

這個(gè)小監(jiān)控思路很清晰,還可以繼續(xù)修改,比如:監(jiān)控特定的接口,發(fā)送短信通知等等。
因?yàn)橛腥罩編?,就少了去線上正式環(huán)境掃描日志的麻煩,所以,如果沒有日志庫,就要自己上線上環(huán)境掃描,在正式線上環(huán)境一定要小心哇~

相關(guān)文章

  • python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼

    python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼

    這篇文章主要介紹了python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-06-06
  • 一個(gè)基于flask的web應(yīng)用誕生 bootstrap框架美化(3)

    一個(gè)基于flask的web應(yīng)用誕生 bootstrap框架美化(3)

    一個(gè)基于flask的web應(yīng)用誕生第三篇,這篇文章主要介紹了前端框架bootstrap與flask框架進(jìn)行整合,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • Python中私有屬性的定義方式

    Python中私有屬性的定義方式

    這篇文章主要介紹了Python中私有屬性的定義方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Pycharm調(diào)試程序技巧小結(jié)

    Pycharm調(diào)試程序技巧小結(jié)

    這篇文章主要介紹了Pycharm調(diào)試程序技巧,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • python getopt模塊使用實(shí)例解析

    python getopt模塊使用實(shí)例解析

    這篇文章主要介紹了python getopt模塊使用實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Python小技巧練習(xí)分享

    Python小技巧練習(xí)分享

    這篇文章主要介紹了Python小技巧練習(xí)分享,文章基于python的相關(guān)內(nèi)容展開詳細(xì)的python小技巧內(nèi)容,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-05-05
  • python爬蟲中采集中遇到的問題整理

    python爬蟲中采集中遇到的問題整理

    在本篇文章里小編給大家整理了關(guān)于python爬蟲中采集中遇到的問題整理內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。
    2020-11-11
  • 用python實(shí)現(xiàn)詞云效果實(shí)例介紹

    用python實(shí)現(xiàn)詞云效果實(shí)例介紹

    大家好,本篇文章主要講的是用python實(shí)現(xiàn)詞云效果實(shí)例介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01
  • Python super( )函數(shù)用法總結(jié)

    Python super( )函數(shù)用法總結(jié)

    今天給大家?guī)淼闹R是關(guān)于Python的相關(guān)知識,文章圍繞著super( )函數(shù)展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • python進(jìn)階教程之詞典、字典、dict

    python進(jìn)階教程之詞典、字典、dict

    這篇文章主要介紹了python進(jìn)階教程之詞典、字典、dict,說了好幾個(gè)詞最官方的應(yīng)該是字典,英文dict,本文就是專注講解字典的,需要的朋友可以參考下
    2014-08-08

最新評論