

自己动手打造性能监控平台
source link: https://mp.weixin.qq.com/s?__biz=MzIxMTg4NDg0MA%3D%3D&%3Bmid=2247485417&%3Bidx=1&%3Bsn=a7f142d91f6ea08a9926a8f5a619e639
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在做性能测试的时候,你是如何监控被测试系统的硬件资源的,如果是云平台,那么一般提供的有可视化的监控信息,如果是本地服务,只能通过系统命令(如ps、top、lsof等)查看。
我们可以自己打造一个可视化的系统系统资源监控平台,本文就教大家如何实现。
准备工具:
-
Flask: 一个简单的web框架。
-
psutil: 用于获取本地硬件信息。
-
flask_socketio:基于Flask框架的websocket库,用于建立长连接。
-
echarts:用于实现各种图表的UI库。
开始动手
下面介绍大体思路,文末有源码:
制作一个监控页面。
https://themes.getbootstrap.com/
booststrap提供了各种各样主题,年轻人不用讲武德,偷袭~!不对,你可以抄袭一个过来。
具体方式就浏览器右键查看源码,复制粘贴,替换JS、CSS 一气呵成~!
制作图表
https://echarts.apache.org/zh/index.html
echarts是一个apache开源的图表UI库,可以帮你生成各种图表。
官方给的实例还还是比较简单的,你可照着例子熟悉一个图表的配置。
获取系统资源
https://pypi.org/project/psutil/
pstil 用于获取本地硬件资源信息,CPU、内存、磁盘等信息。
简单的API:
>>> import psutil >>> psutil.cpu_times() >>> psutil.cpu_count() >>> psutil.swap_memory() >>> psutil.virtual_memory() >>> ....
实时获取系统资源
前端看到的数据一定要是实时的,动态的,那么就要求前端与后端保持数据的交互,websocket就是解决这类问题而生的。
-
后端:
Flask-SocketIO
https://github.com/miguelgrinberg/Flask-SocketIO
-
前端:
socket.io.js
https://socket.io/
后端实现主要代码:
import time import psutil from flask import Flask, render_template, session, request from flask_socketio import SocketIO, emit from threading import Lock app = Flask(__name__, template_folder='./') app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, cors_allowed_origins='*') cpu_thread = None cpu_thread_lock = Lock() @app.route('/') def index(): """ Web页面 """ return render_template('index.html') @socketio.on('connect', namespace='/get_cpu') def cpu_connect(): global cpu_thread with cpu_thread_lock: if cpu_thread is None: cpu_thread = socketio.start_background_task(target=cpu_background_thread) def cpu_background_thread(): count = 0 while True: count += 1 socketio.sleep(5) t = time.strftime('%H:%M:%S', time.localtime()) cpu = psutil.cpu_percent(interval=None, percpu=True) socketio.emit('server_response', {'data': [t, cpu], 'count': count}, namespace='/get_cpu') if __name__ == '__main__': socketio.run(app, host='127.0.0.1', port=9090, debug=True)
这里用到了多线程,每隔5秒向前端发送一次cpu信息。
前端实现主要代码:
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script> <script type="text/javascript"> $(document).ready(function () { var socket = io.connect('http://127.0.0.1:9090/get_cpu', { transports: ['websocket'] }); socket.on('server_response', function (res) { console.log("cpu:", res.data); update_mychart(res); }); </script>
前端建立socket连接,等待服务器“推送”数据,用回调函数更新图表。
源码
感兴趣的可以查看源码:
https://github.com/defnngj/learning-API-test/tree/master/sys_monitoring
我花了两个晚上写的,时间比较短~!大概实现了,优化的地方还有很多。
(虫师的微信号,有偿解答测试相关问题~!)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK