数据存储:
import mysql.connector from sqlalchemy import create_engine # 创建引擎 from sqlalchemy.orm import sessionmaker # 创建会话 class ORM: # 会话方法 @classmethod def db(cls): mysql_configs = dict( db_host="127.0.0.1", # 主机地址 db_name="monitor", # 数据库名称 db_port=3306, # 数据库端口 db_user="root", # 数据库用户 db_pwd="t" # 数据库密码 ) link = "mysql+mysqlconnector://{db_user}:{db_pwd}@{db_host}:{db_port}/{db_name}?charset=utf8".format( **mysql_configs ) # 创建引擎 engine = create_engine( link, encoding="utf-8", echo=False, pool_size=100, pool_recycle=10, connect_args={'charset': 'utf8'} ) # 创建会话 Session = sessionmaker( bind=engine, autocommit=False, autoflush=True, expire_on_commit=False ) return Session()
日志函数:
# -*- coding: utf-8 -*- import time import datetime from app.models.models import Cpu, Mem, Swap from app.tools.monitor import Monitor from app.tools.orm import ORM # 日期时间函数 def dt(): now = datetime.datetime.now() _date_time = now.strftime("%Y-%m-%d %H:%M:%S") _date = now.strftime("%Y-%m-%d") _time = now.strftime("%H:%M:%S") return _date, _time, _date_time # 定义保存日志的函数 def save_log(): m = Monitor() cpu_info, mem_info, swap_info = m.cpu(), m.mem(), m.swap() _date, _time, _date_time = dt() # 1.创建会话 session = ORM.db() try: # CPU cpu = Cpu( percent=cpu_info["percent_avg"], create_date=_date, create_time=_time, create_dt=_date_time ) # 内存 mem = Mem( percent=mem_info['percent'], total=mem_info['total'], used=mem_info['used'], free=mem_info['free'], create_date=_date, create_time=_time, create_dt=_date_time ) # 交换分区 swap = Swap( percent=swap_info['percent'], total=swap_info['total'], used=swap_info['used'], free=swap_info['free'], create_date=_date, create_time=_time, create_dt=_date_time ) # 提交至数据块 session.add(cpu) session.add(mem) session.add(swap) except Exception as e: session.rollback() # 如果发送异常回滚 else: session.commit() # 没有异常提交 finally: session.close() # 无论是否发生异常关闭 if __name__ == "__main__": while True: _date, _time, _date_time = dt() print("开始时间:{}".format(_date_time)) save_log() print("结束时间:{}".format(_date_time)) time.sleep(5) # 每隔5秒采集一次
可视化折线图处理:
# -*- coding: utf-8 -*- import datetime from pyecharts import Liquid, Gauge, Pie, Line class Chart(object): 。。。。。。。 # 折线面积图 def line_html(self, title, key, val, color=None): line = Line( title, title_pos="center", width="100%", height=300 ) line.add( "", key, val, mark_point=["average", "max", "min"], mark_line=["average", "max", "min"], area_color=color, line_opacity=0.2, area_opacity=0.4, is_datazoom_show=True, datazoom_range=[0, 100], symbol=None ) return line.render_embed() # 折线面积图 def line_three_html(self, title, key, val_min, val_max, val_avg): line = Line( title, title_pos="left", width="100%", height=300 ) line.add( "最小值", key, val_min, mark_point=["average", "max", "min"], is_datazoom_show=True, datazoom_range=[0, 100], is_smooth=True ) line.add( "最大值", key, val_max, mark_point=["average", "max", "min"], is_datazoom_show=True, datazoom_range=[0, 100], is_smooth=True ) line.add( "平均值", key, val_avg, mark_point=["average", "max", "min"], is_datazoom_show=True, datazoom_range=[0, 100], is_smooth=True ) return line.render_embed() # 日期时间方法 @property def dt(self): return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
视图:
# -*- coding: utf-8 -*- import tornado.gen import tornado.concurrent from app.views.views_common import CommonHandler from app.tools.monitor import Monitor from app.tools.chart import Chart # 定义一个首页视图 class IndexHandler(CommonHandler): @tornado.gen.coroutine def get(self, *args, **kwargs): yield self.get_response() @tornado.concurrent.run_on_executor def get_response(self): m = Monitor() c = Chart() cpu_info = m.cpu() mem_info = m.mem() swap_info = m.swap() net_info = m.net() disk_info = m.disk() net_pie = [ c.pie_two_html( "net{}".format(k + 1), "{}网卡信息".format(v["name"]), "收发包数统计", "收发字节统计", ["收包数", "发包数"], ["收字节", "发字节"], [v["packets_recv"], v["packets_sent"]], [v["bytes_recv"], v["bytes_sent"]], ) for k, v in enumerate(net_info) if v["packets_recv"] and v['packets_sent'] ] self.html("index.html", data=dict( title="系统监控", cpu_info=cpu_info, mem_info=mem_info, swap_info=swap_info, net_info=net_info, disk_info=disk_info, cpu_liquid=c.liquid_html("cpu_avg", "CPU平均使用率", cpu_info['percent_avg']), mem_gauge=c.gauge_html("mem", "内存使用率", mem_info['percent']), swap_gauge=c.gauge_html("swap", "交换分区使用率", mem_info['percent']), net_pie=net_pie, ) )
路由配置:
# -*- coding: utf-8 -*- from sockjs.tornado import SockJSRouter # 定义路由的 from app.views.views_index import IndexHandler as index # 导入系统监控视图 from app.views.views_log import LogHandler as log # 导入日志监控视图 from app.views.views_real_time import RealTimeHandler as real_time from app.views.views_test import TestHandler as test # 配置路由视图映射规则 urls = [ (r"/", index), (r"/test/", test), (r"/log/", log), ] + SockJSRouter(real_time, "/real/time").urls
结果:
本文来自博客园,作者:topass123,转载请注明原文链接:https://www.cnblogs.com/topass123/p/13125354.html