カスタムメトリクス

メトリクスの公開

コードにカスタムメトリクスを接続すると、リアルタイムでコード内の値を監視できます。

クイックスタート

最初にtx2モジュールをインストールします

$ npm install tx2

次に、monit.jsと呼ばれるアプリを作成します

const tx2 = require('tx2')
const http = require('http')

let meter = tx2.meter({
  name      : 'req/sec',
  samples   : 1,
  timeframe : 60
})

http.createServer((req, res) => {
  meter.mark()
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.write('Hello World!')
  res.end()
}).listen(6001)

そしてPM2で開始します

$ pm2 start monit.js

コマンドでメトリクスを表示します

$ pm2 show [app]
# pm2 show monit

: メトリクスは「カスタムメトリクス」セクションにあります。

または、ターミナルベースのインターフェイスを使用できます

$ pm2 monit

利用可能なメトリクスヘルパー

その後、重要な情報を追跡するために独自のメトリクスをプログラムできます。4つの異なるプローブを利用できます

  • 単純なメトリクス: 即座に読み取ることができる値
    • 例: 変数値の監視
  • カウンター: 増減するもの
    • 例: 処理中のダウンロード、接続中のユーザー
  • メーター: イベント/間隔として測定されるもの
    • 例: HTTPサーバーの1分あたりのリクエスト数
  • ヒストグラム: 過去5分間に偏った統計的に関連する値のリザーバーを保持し、それらの分布を調査します
    • 例: データベースへのクエリの実行の平均を監視します

APIドキュメント

: TX2 APIドキュメントを参照します

単純なメトリクス: 単純な値の報告

瞬時に読み取ることができる値を公開できるようにします。

const tx2 = require('tx2')

// Here the value function will be called each second to get the value
var metric = tx2.metric({
  name    : 'Realtime user',
  value   : function() {
    return Object.keys(users).length
  }
})

// Here we are going to call valvar.set() to set the new value
var valvar = tx2.metric({
  name    : 'Realtime Value'
})

valvar.set(23)

カウンター: 連続的な値の変更

増減する値。

アクティブHTTPリクエストをカウントする例

const tx2 = require('tx2')
var http = require('http')

var counter = tx2.counter({
  name : 'Active requests'
})

http.createServer(function (req, res) {
  counter.inc()

  req.on('end', function() {
    // Decrement the counter, counter will eq 0
    counter.dec()
  })
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.write('Hello World!')
  res.end()
}).listen(6001)

メーター: 計算された平均値

イベント/間隔として測定される値。

1秒あたりのクエリ数をカウントする例

const tx2 = require('tx2')
var http = require('http')

var meter = tx2.meter({
  name      : 'req/sec',
  samples   : 1,
  timeframe : 60
})

http.createServer(function (req, res) {
  meter.mark()
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.write('Hello World!')
  res.end()
}).listen(6001)
オプション

samplesオプションはレート単位です。デフォルトは1秒です。timeframeオプションはイベントが分析される期間です。デフォルトは60秒です。

ヒストグラム

過去5分間に偏った統計的に関連する値のリザーバーを保持して、それらの分布を調べます。

const tx2 = require('tx2')

var histogram = tx2.histogram({
  name        : 'latency',
  measurement : 'mean'
})

var latency = 0

setInterval(function() {
  latency = Math.round(Math.random() * 100)
  histogram.update(latency)
}, 100)
このページに寄稿する