用于 Ruby 应用程序的 Prometheus 仪表库
A suite of instrumentation metric primitives for Ruby that can be exposed through a HTTP interface. Intended to be used together with a [Prometheus server][1].
![Gem Version][4] ![Build Status][3]
For a global installation run gem install prometheus-client.
If you're using Bundler add gem "prometheus-client" to your Gemfile.
Make sure to run bundle install afterwards.
require 'prometheus/client'
# returns a default registry
prometheus = Prometheus::Client.registry
# create a new counter metric
http_requests = Prometheus::Client::Counter.new(:http_requests, docstring: 'A counter of HTTP requests made')
# register the metric
prometheus.register(http_requests)
# equivalent helper function
http_requests = prometheus.counter(:http_requests, docstring: 'A counter of HTTP requests made')
# start using the counter
http_requests.incrementThere are two [Rack][2] middlewares available, one to expose a metrics HTTP endpoint to be scraped by a Prometheus server ([Exporter][9]) and one to trace all HTTP requests ([Collector][10]).
It's highly recommended to enable gzip compression for the metrics endpoint,
for example by including the Rack::Deflater middleware.
# config.ru
require 'rack'
require 'prometheus/middleware/collector'
require 'prometheus/middleware/exporter'
use Rack::Deflater
use Prometheus::Middleware::Collector
use Prometheus::Middleware::Exporter
run ->(_) { [200, {'content-type' => 'text/html'}, ['OK']] }Start the server and have a look at the metrics endpoint: http://localhost:5123/metrics.
For further instructions and other scripts to get started, have a look at the integrated example application.
The Ruby client can also be used to push its collected metrics to a [Pushgateway][8]. This comes in handy with batch jobs or in other scenarios where it's not possible or feasible to let a Prometheus server scrape a Ruby process. TLS and HTTP basic authentication are supported.
…By design, Prometheus::Client::Push doesn't read credentials for HTTP basic
authentication when they are passed in via the gateway URL using the
http://user:[email protected]:9091 syntax, and will in fact raise an error if they're
supplied that way.
The reason for this is that when using that syntax, the username and password have to follow the usual rules for URL encoding of characters per RFC 3986.
Rather than place the burden of correctly performing that encoding on users of this gem, we decided to have a separate method for supplying HTTP basic authentication credentials, with no requirement to URL encode the characters in them.
Instead of passing credentials like this:
push = Prometheus::Client::Push.new(job: "my-job", gateway: "http://user:password@localhost:9091")please pass them like this:
push = Prometheus::Client::Push.new(job: "my-job", gateway: "http://localhost:9091")
push.basic_auth("user", "password")The following metric types are currently supported.
Counter is a metric that exposes merely a sum or tally of things.
counter = Prometheus::Client::Counter.new(:service_requests_total, docstring: '...', labels: [:service])
# increment the counter for a given label set
counter.increment(labels: { service: 'foo' })
# increment by a given value
counter.increment(by: 5, labels: { service: 'bar' })
# get current value for a given label set
counter.get(labels: { service: 'bar' })
# => 5Gauge is a metric that exposes merely an instantaneous value or some snapshot thereof.
gauge = Prometheus::Client::Gauge.new(:room_temperature_celsius, docstring: '...', labels: [:room])
# set a value
gauge.set(21.534, labels: { room: 'kitchen' })
# retrieve the current value for a given label set
gauge.get(labels: { room: 'kitchen' })
# => 21.534
# increment the value (default is 1)
gauge.increment(labels: { room: 'kitchen' })
# => 22.534
# decrement the value by a given value
gauge.decrement(by: 5, labels: { room: 'kitchen' })
# => 17.534A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets. It also provides a sum of all observed values.
histogram = Prometheus::Client::Histogram.new(:service_latency_seconds, docstring: '...', labels: [:service])
# record a value
histogram.observe(Benchmark.realtime { service.call(arg) }, labels: { service: 'users' })
# retrieve the current bucket values
histogram.get(labels: { service: 'users' })
# => { 0.005 => 3, 0.01 => 15, 0.025 => 18, ..., 2.5 => 42, 5 => 42, 10 = >42 }Histograms provide default buckets of [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
You can specify your own buckets, either explicitly, or using the Histogram.linear_buckets
or Histogram.exponential_buckets methods to define regularly spaced buckets.
Summary, similar to histograms, is an accumulator for samples. It captures Numeric data and provides an efficient percentile calculation mechanism.
For now, only sum and total (count of observations) are supported, no actual quantiles.
summary = Prometheus::Client::Summary.new(:service_latency_seconds, docstring: '...', labels: [:service])
# record a value
summary.observe(Benchmark.realtime { service.call() }, labels: { service: 'database' })
# retrieve the current sum and total values
summary_value = summary.get(labels: { service: 'database' })
summary_value['sum'] # => 123.45
summary_value['count'] # => 100All metrics can have labels, allowing grouping of related time series.
Labels are an extremely powerful feature, but one that must be used with care. Refer to the best practices on naming and labels.
Most importantly, avoid labels that can have a large number of possible values (high cardinality). For example, an HTTP Status Code is a good label. A User ID is not.
Labels are specified optionally when updating metrics, as a hash of label_name => value.
Refer to the Prometheus documentation
as to what's a valid label_name.
In order for a metric to accept labels, their names must be specified when first initializing the metric. Then, when the metric is updated, all the specified labels must be present.
Example:
https_requests_total = Counter.new(:http_requests_total, docstring: '...', labels: [:service, :status_code])
# increment the counter for a given label set
https_requests_total.increment(labels: { service: "my_service", status_code: response.status_code })You can also "pre-set" some of these label values, if they'll always be the same, so you don't need to specify them every time:
https_requests_total = Counter.new(:http_requests_total,
docstring: '...',
labels: [:service, :status_code],
preset_labels: { service: "my_service" })
# increment the counter for a given label set
https_requests_total.increment(labels: { status_code: response.status_code })with_labelsSimilar to pre-setting labels, you can get a new instance of an existing metric object, with a subset (or full set) of labels set, so that you can increment / observe the metric without having to specify the labels for every call.
Moreover, if all the labels the metric can take have been pre-set, validation of the labels
is done on the call to with_labels, and then skipped for each observation, which can
lead to performance improvements. If you are incrementing a counter in a fast loop, you
definitely want to be doing this.
Examples:
Pre-setting labels for ease of use:
…init_label_setThe time series of a metric are not initialized until something happens. For counters, for example, this means that the time series do not exist until the counter is incremented for the first time.
To get around this problem the client provides the init_label_set method that can be used to initialise the time series of a metric for a given label set.
The following labels are reserved by the client library, and attempting to use them in a
metric definition will result in a
Prometheus::Client::LabelSetValidator::ReservedLabelError being raised:
:job:instance:pidThe data for all the metrics (the internal counters associated with each labelset) is stored in a global Data Store object, rather than in the metric objects themselves. (This "storage" is ephemeral, generally in-memory, it's not "long-term storage")
The main reason to do this is that different applications may have different requirements for their metrics storage. Applications running in pre-fork servers (like Unicorn, for example), require a shared store between all the processes, to be able to report coherent numbers. At the same time, other applications may not have this requirement but be very sensitive to performance, and would prefer instead a simpler, faster store.
By having a standardized and simple interface that metrics use to access this store, we abstract away the details of storing the data from the specific needs of each metric. This allows us to then simply swap around the stores based on the needs of different applications, with no changes to the rest of the client.
The client provides 3 built-in stores, but if neither of these is ideal for your requirements, you can easily make your own store and use that instead. More on this below.
By default, the Client uses the Synchronized store, which is a simple, thread-safe Store
for single-process scenarios.
If you need to use a different store, set it in the Client Config:
Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DataStore.new(store_specific_params)NOTE: You must make sure to set the data_store before initializing any metrics.
If using Rails, you probably want to set up your Data Store on config/application.rb,
or config/environments/*, both of which run before config/initializers/*
Also note that config.data_store is set to an instance of a DataStore, not to the
class. This is so that the stores can receive parameters. Most of the built-in stores
don't require any, but DirectFileStore does, for example.
When instantiating metrics, there is an optional store_settings attribute. This is used
to set up store-specific settings for each metric. For most stores, this is not used, but
for multi-process stores, this is used to specify how to aggregate the values of each
metric across multiple processes. For the most part, this is used for Gauges, to specify
whether you want to report the SUM, MAX, MIN, or MOST_RECENT value observed across
all processes. For almost all other cases, you'd leave the default (SUM). More on this
on the Aggregation section below.
Custom stores may also accept extra parameters besides :aggregation. See the
documentation of each store for more details.
There are 3 built-in stores, with different trade-offs:
暂无开放 Issues,或尚未同步最近议题。