导航:首页 > 编程语言 > 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监控时间相关的资料

热点内容
at89c51编程器 浏览:341
项目经理叫醒程序员 浏览:342
autocad旋转命令 浏览:660
手机版wpsoffice怎么打包文件夹 浏览:579
在成都学车用什么app 浏览:818
grep命令管道 浏览:426
java修改重启 浏览:567
单片机供电方案 浏览:770
airpodspro一代怎么连接安卓 浏览:218
豌豆荚app上有什么游戏 浏览:283
公路商店app标签选什么 浏览:339
linuxoracle命令行登录 浏览:227
android深度休眠 浏览:173
php微信开发例子 浏览:846
医得app登录密码是什么 浏览:142
spring开发服务器地址 浏览:411
服务器上如何查看服务器的端口 浏览:678
单片机服务器编译 浏览:770
单口usb打印机服务器是什么 浏览:859
战地五开服务器要什么条件 浏览:956