導航:首頁 > 編程語言 > python監控時間

python監控時間

發布時間:2023-01-19 14:41:02

Ⅰ 有python開發的監控工具嗎

在公司里做的一個介面系統,主要是對接第三方的系統介面,所以,這個系統里會和很多其他公司的項目交互。隨之而來一個很蛋疼的問題,這么多公司的介面,不同公司介面的穩定性差別很大,訪問量大的時候,有的不怎麼行的介面就各種出錯了。
這個介面系統剛剛開發不久,整個系統中,處於比較邊緣的位置,不像其他項目,有日誌庫,還有簡訊告警,一旦出問題,很多情況下都是用戶反饋回來,所以,我的想法是,拿起python,為這個項目寫一個監控。如果在調用某個第三方介面的過程中,大量出錯了,說明這個介面有有問題了,就可以更快的採取措施。
項目的也是有日誌庫的,所有的info,error日誌都是每隔一分鍾掃描入庫,日誌庫是用的mysql,表裡有幾個特別重要的欄位:
有日誌庫,就不用自己去線上環境掃日誌分析了,直接從日誌庫入手。由於日誌庫在線上時每隔1分鍾掃,那我就去日誌庫每隔2分鍾掃一次,如果掃到有一定數量的error日誌就報警,如果只有一兩條錯誤就可以無視了,也就是短時間爆發大量錯誤日誌,就可以斷定系統有問題了。報警方式就用發送郵件,所以,需要做下面幾件事情:
1. 操作MySql。
2. 發送郵件。
3. 定時任務。
4. 日誌。
5. 運行腳本。
明確了以上幾件事情,就可以動手了。
操作資料庫
使用MySQLdb這個驅動,直接操作資料庫,主要就是查詢操作。
獲取資料庫的連接:

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分鍾的數據,首先,根據當前時間進行計算一下時間。之前,計算有問題,現在已經修改。

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

發送郵件
使用python發送郵件比較簡單,使用標准庫smtplib就可以
這里使用163郵箱進行發送,你可以使用其他郵箱或者企業郵箱都行,不過host和port要設置正確。

def send_email(content):

sender = "[email protected]"
receiver = ["[email protected]", "[email protected]"]
host = 'smtp.163.com'
port = 465
msg = MIMEText(content)
msg['From'] = "[email protected]"
msg['To'] = "[email protected],[email protected]"
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條,就發郵件通知。

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)

所以,最後,這個監控小程序就是這樣的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 = "[email protected]"
receiver = ["[email protected]", "[email protected]"]
host = 'smtp.163.com'
port = 465
msg = MIMEText(content)
msg['From'] = "[email protected]"
msg['To'] = "[email protected],[email protected]"
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查看腳本的運行狀態。
總結
這個小監控思路很清晰,還可以繼續修改,比如:監控特定的介面,發送簡訊通知等等。
因為有日誌庫,就少了去線上正式環境掃描日誌的麻煩,所以,如果沒有日誌庫,就要自己上線上環境掃描,在正式線上環境一定要小心哇~

Ⅱ 如何在Windows下使用Python監控文件變動

有一個API,注冊後,文件發生變動,它會自動通知你。

另外還有一個辦法,似乎是以特定方式,打開文件,當有人修改這個文件時,你會獲得通知。

還有監控目錄的辦法。

最笨的辦法當然是定時輪詢。不需要什麼技巧,定時檢查文件和目錄的修改時間,如果時間發生變化就是變動了。

Ⅲ python監控區域網文件夾

直接改IP地址可能不行,建議在內網把該目錄發布成ftp或者http,通過這2種方式訪問,獲取文件修改時間吧。

Ⅳ 有什麼工具可以監控到我打開一個系統的整個操作,然後統計打開每個頁簽載入完成的時間,python能實現不

看提問應該是打開一個web應用,可以使用python selenum實現瀏覽器相應操作並計時。網頁鏈接

Ⅳ 如何用 Python 監控系統狀態

建立一個資料庫「falcon」,建表語句如下:
CREATE TABLE `stat` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`host` varchar(256) DEFAULT NULL,
`mem_free` int(11) DEFAULT NULL,
`mem_usage` int(11) DEFAULT NULL,
`mem_total` int(11) DEFAULT NULL,
`load_avg` varchar(128) DEFAULT NULL,
`time` bigint(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `host` (`host`(255))
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

Ⅵ python 監控視頻分析

Python有個非常強的庫叫OpenCV,這個庫操作很簡單,可以打開視頻文件做截圖,這個OpenCV庫還提供了兩張圖片的比較功能。
你可以先把視頻每秒截圖一張。
然後只要把連續的截圖後一張對前一張比較,找到差異大的就可以發現圖像有變化

了。

Ⅶ 7種檢測Python程序運行時間、CPU和內存佔用的方法

1. 使用裝飾器來衡量函數執行時間

有一個簡單方法,那就是定義一個裝飾器來測量函數的執行時間,並輸出結果:

import time

from functoolsimport wraps

import random

def fn_timer(function):

  @wraps(function)

  def function_timer(*args, **kwargs):

      t0= time.time()

      result= function(*args, **kwargs)

      t1= time.time()

      print("Total time running %s: %s seconds" %

          (function.__name__, str(t1- t0))

)

      return result

return function_timer

@fn_timer

def random_sort(n):

  return sorted([random.random() for i in range(n)])

if __name__== "__main__":

  random_sort(2000000)

輸出:Total time running random_sort: 0.6598007678985596 seconds

使用方式的話,就是在要監控的函數定義上面加上 @fn_timer 就行了

或者

# 可監控程序運行時間

import time

import random

def clock(func):

    def wrapper(*args, **kwargs):

        start_time= time.time()

        result= func(*args, **kwargs)

        end_time= time.time()

        print("共耗時: %s秒" % round(end_time- start_time, 5))

        return result

return wrapper

@clock

def random_sort(n):

  return sorted([random.random() for i in range(n)])

if __name__== "__main__":

  random_sort(2000000)

輸出結果:共耗時: 0.65634秒

2. 使用timeit模塊

另一種方法是使用timeit模塊,用來計算平均時間消耗。

執行下面的腳本可以運行該模塊。

這里的timing_functions是Python腳本文件名稱。

在輸出的末尾,可以看到以下結果:4 loops, best of 5: 2.08 sec per loop

這表示測試了4次,平均每次測試重復5次,最好的測試結果是2.08秒。

如果不指定測試或重復次數,默認值為10次測試,每次重復5次。

3. 使用Unix系統中的time命令

然而,裝飾器和timeit都是基於Python的。在外部環境測試Python時,unix time實用工具就非常有用。

運行time實用工具:

輸出結果為:

Total time running random_sort: 1.3931210041 seconds

real 1.49

user 1.40

sys 0.08

第一行來自預定義的裝飾器,其他三行為:

    real表示的是執行腳本的總時間

    user表示的是執行腳本消耗的CPU時間。

    sys表示的是執行內核函數消耗的時間。

注意:根據維基網路的定義,內核是一個計算機程序,用來管理軟體的輸入輸出,並將其翻譯成CPU和其他計算機中的電子設備能夠執行的數據處理指令。

因此,Real執行時間和User+Sys執行時間的差就是消耗在輸入/輸出和系統執行其他任務時消耗的時間。

4. 使用cProfile模塊

5. 使用line_profiler模塊

6. 使用memory_profiler模塊

7. 使用guppy包

Ⅷ python ftplib監控文件修改時間

用python的ftplib,示例代碼如下,返回目錄內容的詳細信息,自己做下相應的處理就可以了

fromftplibimportFTP

ftp=FTP()
timeout=30
port=21
ftp.connect('192.168.85.1',port,timeout)#連接FTP伺服器
ftp.login('test','test')#登錄
printftp.getwelcome()#獲得歡迎信息
ftp.cwd('test')#設置FTP路徑
printftp.retrlines('LIST')#列出目錄內容

Ⅸ 用python怎麼不刷新網頁而監控網頁變化

在瀏覽器第一次請求某一個URL時,伺服器端的返回狀態會是200,內容是你請求的資源,同時有一個Last-Modified的屬性標記此文件在服務期端最後被修改的時間,格式類似這樣:
Last-Modified: Fri, 12 May 2006 18:53:33 GMT 客戶端第二次請求此URL時,根據 HTTP
協議的規定,瀏覽器會向伺服器傳送 If-Modified-Since 報頭,詢問該時間之後文件是否有被修改過:
If-Modified-Since: Fri, 12 May 2006 18:53:33 GMT
如果伺服器端的資源沒有變化,則自動返回 HTTP 304 (Not
Changed.)狀態碼,內容為空,這樣就節省了傳輸數據量。當伺服器端代碼發生改變或者重啟伺服器時,則重新發出資源,返回和第一次請求時類似。從而保證不向客戶端重復發出資源,也保證當伺服器有變化時,客戶端能夠得到最新的資源。

headers'If-Modified-Since'

Status Code:304 Not Modified

狀態碼 304 表示頁面未改動

>>> import requests as req>>> url='http://www.guancha.cn/'>>> rsp=req.head(url,headers={'If-Modified-Since':'Sun, 05 Feb 2017 05:39:11 GMT'})>>> rsp
<Response [304]>>>> rsp.headers
{'Server': 'NWS_TCloud_S1', 'Content-Type': 'text/html', 'Date': 'Sun, 05 Feb 2017 05:45:20 GMT', 'Cache-Control': 'max-age=60', 'Expires': 'Sun, 05 Feb 2017 05:46:20 GMT', 'Content-Length': '0', 'Connection': 'keep-alive'}

時間改為 昨天(4號)

伺服器返回狀態碼200

並且有'Last-Modified': 'Sun, 05 Feb 2017 06:00:03 GMT'

表示 最後修改的時間。

>>> hds={'If-Modified-Since':'Sat, 04 Feb 2017 05:39:11 GMT'} # 時間改為 昨天(4號)>>> rsp=req.head(url,headers=hds)>>> rsp
<Response [200]>>>> rsp.headers
{'Last-Modified': 'Sun, 05 Feb 2017 06:00:03 GMT', 'Date': 'Sun, 05 Feb 2017 06:04:59 GMT', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'X-Daa-Tunnel': 'hop_count=2', 'X-Cache-Lookup': 'Hit From Disktank3 Gz, Hit From Inner Cluster, Hit From Upstream', 'Server': 'nws_ocmid_hy', 'Content-Type': 'text/html', 'Expires': 'Sun, 05 Feb 2017 06:05:59 GMT', 'Cache-Control': 'max-age=60', 'Content-Length': '62608'}>>>

Ⅹ python 監控一個文件夾

監控,其實就是周期性的啟動判斷程序。
這判斷程序要看你的具體需求,也就文件怎麼算修改了:判斷文件大小?讀取最後修改時間?還是讀取文件和原文件進行比較?
周期性執行,簡單的就弄個循環就行,這樣程序必須一直運行,不可靠,因為程序可能會被關閉。
所以最好是把程序做成系統服務。
發郵件就比較簡單,網上一堆現成的源碼

閱讀全文

與python監控時間相關的資料

熱點內容
豌豆莢app上有什麼游戲 瀏覽:283
公路商店app標簽選什麼 瀏覽:337
linuxoracle命令行登錄 瀏覽:224
android深度休眠 瀏覽:169
php微信開發例子 瀏覽:843
醫得app登錄密碼是什麼 瀏覽:140
spring開發伺服器地址 瀏覽:411
伺服器上如何查看伺服器的埠 瀏覽:678
單片機伺服器編譯 瀏覽:770
單口usb列印機伺服器是什麼 瀏覽:859
戰地五開伺服器要什麼條件 瀏覽:956
在word中壓縮圖片大小 瀏覽:255
javatomcat圖片 瀏覽:419
程序員生產智能創意 瀏覽:67
匯和銀行app怎麼登錄 瀏覽:383
騰訊伺服器如何上傳源碼 瀏覽:749
單片機的原理概述 瀏覽:512
火控pdf 瀏覽:270
如何復制雲伺服器centos環境 瀏覽:988
債權pdf 瀏覽:307