test_counter = prometheus.count(:test_count, 'A test counter')
使用increment方法来增加指标的值
代码清单:增加指标的值
代码语言:javascript复制
test_counter.increment
代码清单:查询指标的值
代码语言:javascript复制
test_counter.get
1.0
可以注册多种类型的指标,包括摘要和直方图
代码清单:基本的Prometheus client_ruby指标
代码语言:javascript复制
test_counter = prometheus.counter(:test_counter, 'A test counter')
test_gauge = prometheus.gauge(:test_gauge, 'A test gauge')
test_histogram = prometheus.histogram(:test_histogram, 'A test histogram')
test_summary = prometheus.summary(:test_summary, 'A test summary')
将监控添加到Rails
我们不希望每次记录指标时,都需要手动创建注册表和指标,所以用实用程序代码来执行此操作
代码清单:创建Metrics模块
代码语言:javascript复制
touch lib/metrics.rb
代码清单:Metrics模块
代码语言:javascript复制
module Metrics
def self.counter(name, docstring, base_labels = {})
provide_metric(name) || registry.counter(name, docstring, base_labels)
end
def self.summary(name, docstring, base_labels = {})
provide_metric(name) || registry.summary(name, docstring, base_labels)
end
def self.gauge(name, docstring, base_labels = {})
provide_metric(name) || registry.summary(name, docstring, base_labels)
end
def self.histogram(name, docstring, base_labels = {}, buckets = ::Prometheus::Clien::Histogram::DEFAULT_BUCKETS)
provide_metric(name) || registry.histogram(name, docstring, base_labels, buckets)
end
private
def self.provide_metrics(name)
registry.get(name)
end
def. self.registry
@registry || ::Prometheus::Client.registry
end
end
def destroy
user = User.find(params[:id])
user.destroy
Metrics.counter(:users_deletes_counter, "Deletes users counter").increment
redirect_to users_path, :notice => "User deleted."
end
还可以使用increment方法添加标签或者指定增量,如下所示
代码语言:javascript复制
.increment({service: 'foo'}, 2)
还可以为所建用户构建另一个计数器并添加到User模型
代码清单:创建用户的计数器
代码语言:javascript复制
class User < ActiveRecord::Base
enum role: [:user, :vip, :admin]
after_initialize :set_default, :if => :new_record?
after_create do
Metrics.counter(:user_created_counter, "Users created counter").increment
end
end
require 'prometheus/middleware/collector'
require 'prometheus/middleware/exporter'
use Prometheus::Middleware::Collector
use Prometheus::Middleware::Exporter