监控Linux服务器的工具、组件和程序网上有很多,但是一台服务器上会有很多进程同时运行,特别是做性能测试的时候,可能一台服务器上部署多个服务,如果只监控整个服务器的CPU和内存,当某个服务出现性能问题时,并不能有效准确的定位出(当然通过其他工具也可以实现),因此,很有必要只监控指定的进程。需求明确了,于是动手撸了一个性能监控脚本。
一、整体思路
1、为了方便的启动监控和停止监控,在想查看监控结果的时候随时查看监控结果,用flask开启了一个服务,通过发送get请求可以随时启停监控和查看监控结果。
2、针对控制是否监控cpu、内存、IO,开启多线程监控。
3、为了减少对其他组件的依赖,将监控结果写到日志中。
4、为了方便查看监控结果,直接将结果以html方式返回。
二、配置文件
config.py
IP = '127.0.0.1'
PORT = '5555'
LEVEL = 'INFO' # log level
BACKUP_COUNT = 9 # log backup counter
LOG_PATH = 'logs' # log path
INTERVAL = 1 # interval, run command interval.
SLEEPTIME = 3 # interval, when stopping monitor, polling to start monitor when satisfying condition.
ERROR_TIMES = 5 # times, number of running command. When equal, automatically stopped monitor.
IS_JVM_ALERT = True # Whether to alert when the frequency of Full GC is too high.
IS_MONITOR_SYSTEM = True # Whether to monitor system's CPU and Memory.
IS_MEM_ALERT = True # Whether to alert when memory is too low. Alert by sending email.
MIN_MEM = 2 # Minxium memory, uint: G
# 0: don't clear cache, 1: clear page caches, 2: clear dentries and inodes caches, 3: include 1 and 2;
# echo 1 >/proc/sys/vm/drop_caches
ECHO = 0
SMTP_SERVER = 'smtp.sina.com' # SMTP server
SENDER_NAME = '张三' # sender name
SENDER_EMAIL = '[email protected]' # sender's email
PASSWORD = 'UjBWYVJFZE9RbFpIV1QwOVBUMDlQUT09' # email password, base64 encode.
RECEIVER_NAME = 'baidu_all' # receiver name
RECEIVER_EMAIL = ['[email protected]', '[email protected]'] # receiver's email
DISK = 'device1' # Which disk your application runs
START_TIME = 'startTime.txt' # Store the time of start monitoring.
FGC_TIMES = 'FullGC.txt' # Store the time of every FullGC time.
# html
HTML = '<html><body>{}</body><html>'
ERROR = '<p style="color:red">{}</p>'
HEADER = '<div>六、扩展函数
extern.py 有两个功能
1、端口转进程
try:
result = os.popen(f’netstat -nlp|grep {port} |tr -s ” “‘).readlines()
res = [line.strip() for line in result if str(port) in line]
p = res[0].split(‘ ‘)
pp = p[3].split(‘:’)[-1]
if str(port) == pp:
pid = p[-1].split(‘/’)[0]
except Exception as err:
logger.logger.error(err)2、查找包含监控结果的日志
整体思路:
(1)根据输入的开始时间和结束时间,查找包含这段时间的所有日志文件;
(2)根据查找出来的日志文件,找出包含监控结果的所有日志;
(3)画图的时候遍历找出的所有日志。补充
1、为了方便查看最近一次开始监控的时间,会将每一次开始监控的时间写到startTime.txt文件中;
2、为了方便排查java应用可能出现的问题,将每一次Full GC的时间写到FullGC.txt文件中。
项目地址:https://github.com/leeyoshinari/performance_monitor
总结
以上所述是小编给大家介绍的基于python的Linux系统指定进程性能监控,大家如有疑问可以留言,或者联系站长。感谢亲们支持!!!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!香港服务器首选树叶云,2H2G首月10元开通。
树叶云(www.IDC.Net)提供简单好用,价格厚道的香港/美国云服务器和独立服务器。IDC+ISP+ICP资质。ARIN和APNIC会员。成熟技术团队15年行业经验。文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/169111.html<