socket.ioとchart.jsを使ってメモリ利用率をグラフ表示

まずはchart.jsを表示するHTML

[index.html]

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Server HealthCheck</title>
  <script src="https://[your socket server]/socket.io/socket.io.js"></script>
</head>
<body>
    <div style="position:absolute; top:60px; left:10px; width:500px; height:500px;">
  <canvas id="myChart" style="position: relative; height:100; width:150"></canvas>
    </div>

    <script src="/chartjs/moment/moment.js"></script>
    <script src="/chartjs/chart.js/dist/Chart.js"></script>
    <script src="/chartjs/chartjs-plugin-streaming.js"></script>
    <script src="/js/health.js"></script>
</body>
</html>

canvasを配置して、javascript部分をhealth.jsに作っていきます。

[health.js]

'use strict';
/*
 * Socket.io Setting
 */
let socket = io.connect('https://[your socket server]/');
let useMemPercent = null;

socket.on('connect', (evt) => {
  console.log('[SOCKET IO] socket.io connected.');
});

socket.on('health', (message) => {
        //受信したmessageにはメモリの利用率が数字で入っています。
  useMemPercent = message;

});

//あとはchart.jsのサンプルを少し変更
var chartColors = {
  red: 	'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 	'rgb(75, 192, 192)',
  blue: 	'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 	'rgb(201, 203, 207)'
};

function getUseMemPercent() {
  return useMemPercent;
}

function onRefresh(chart) {
  chart.config.data.datasets.forEach(function(dataset) {
    dataset.data.push({
      x: Date.now(),
      y: getUseMemPercent()
    });
  });
}

var color = Chart.helpers.color;
var config = {
  type: 'line',
  data: {
    datasets: [{
      label: 'Use Memory',
      backgroundColor: color(chartColors.orange).alpha(0.5).rgbString(),
      borderColor: chartColors.blue,
      fill: false,
      lineTension: 0,
      borderDash: [8, 4],
      data: []
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Server Use Memory'
    },
    scales: {
      xAxes: [{
        type: 'realtime',
        realtime: {
          duration: 20000,
          refresh: 1000,
          delay: 2000,
          onRefresh: onRefresh
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'percent'
        },
        ticks: {
          bigenAtZero: true,
          min: 0,
          max: 100
        }
      }]
    }
  }
};

window.onload = function() {
  var ctx = document.getElementById('myChart').getContext('2d');
  window.myChart = new Chart(ctx, config);
};

 

socket.ioサーバにnode.jsを利用します。

[server.js]

module.exports = io => {
  let os = require('os');
  
  io.on('connection', (socket) => {

    console.log('[SOCKET IO] Socket.io New Connection');

    setInterval(cb, 1000);

    function cb(){
      let useMem = os.totalmem() - os.freemem(); 
      let useMemPercent = Math.floor(useMem / os.totalmem() * 100);
      io.emit("health", useMemPercent);
    }

  });
}

 

1秒毎にメモリ使用率がチャートに表示されます。