LoginSignup
0
0

More than 5 years have passed since last update.

Mackerel のServiceMetricsにRubyから値をアップロードする

Posted at

コード

require 'faraday'
require 'faraday_middleware'

class Mackerel
  HOST = 'https://mackerel.io/'.freeze
  API_URL = '/api/v0/services/__SERVICE_NAME__/tsdb'.freeze
  METRICS_PREFIX = '__SERVICE_METRICX_PREFIX__'.freeze

  APIKEY = '___API_TOKEN___'.freeze

  def initialize
    @con = Faraday.new(url: HOST) {|build|
        build.request :json
        build.response :json
        build.adapter Faraday.default_adapter
      }
  end

  def put_metrics(group, metrics)
    post_date = metrics.map {|metric|
        {
          name: "#{METRICS_PREFIX}.#{group}.#{metric.name}",
          # for Rails: time: Time.current.in_time_zone('Tokyo').to_i, 
          time: Time.now.to_i
          value: metric.value
        }
      }

    @con.post {|req|
      req.url(API_URL)
      req.headers['X-Api-Key'] = APIKEY
      req.body = post_date
    }
  end
end

Metric = Struct.new(:name, :value)

metrics = [
  Metric.new('all', 1)
]

mackerel = Mackerel.new
mackerel.put_metrics('ProcessingCount', metrics)

結果

これで __PREFIX__.ProcessingCount.allという感じで入ってくる。
graphのグルーピングは最後の . らしいので、 __PREFIX__.ProcessingCount.* になる。

詳しくは公式ドキュメントがわかりやすいので是非。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0