百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

prometheus_exporter

> 编程语言
开源

用于收集和聚合 Prometheus 指标的框架

584 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

用于收集和聚合 Prometheus 指标的框架

Prometheus Exporter

Prometheus Exporter allows you to aggregate custom metrics from multiple processes and export to Prometheus. It provides a very flexible framework for handling Prometheus metrics and can operate in a single and multiprocess mode.

To learn more see Instrumenting Rails with Prometheus (it has pretty pictures!)

  • Requirements
  • Migrating from v0.x
  • Installation
  • Usage
    • Single process mode
      • Custom quantiles and buckets
    • Multi process mode
    • Rails integration
      • Per-process stats
      • Sidekiq metrics
      • Shoryuken metrics
      • ActiveRecord Connection Pool Metrics
      • Delayed Job plugin
      • Hutch metrics
    • Puma metrics
    • Unicorn metrics
    • Resque metrics
    • GoodJob metrics
    • Custom type collectors
    • Multi process mode with custom collector
    • GraphQL support
    • Metrics default prefix / labels
    • Client default labels
    • Client default host
    • Histogram mode
    • Histogram - custom buckets
  • Transport concerns
  • JSON generation and parsing
  • Logging
  • Docker Usage
  • Contributing
  • License
  • Code of Conduct

Requirements

Minimum Ruby of version 3.0.0 is required, Ruby 2.7 is EOL as of March 31st 2023.

Migrating from v0.x

There are some major changes in v1.x from v0.x.

  • Some of metrics are renamed to match prometheus official guide for metric names. (#184)

Installation

Add this line to your application's Gemfile:

ruby
gem 'prometheus_exporter'

And then execute:

$ bundle

Or install it yourself as:

$ gem install prometheus_exporter

Usage

Single process mode

Simplest way of consuming Prometheus exporter is in a single process mode.

…

Custom quantiles and buckets

You can also choose custom quantiles for summaries and custom buckets for histograms.

ruby

summary = PrometheusExporter::Metric::Summary.new("load_time", "time to load page", quantiles: [0.99, 0.75, 0.5, 0.25])
histogram = PrometheusExporter::Metric::Histogram.new("api_time", "time to call api", buckets: [0.1, 0.5, 1])

Multi process mode

In some cases (for example, unicorn or puma clusters) you may want to aggregate metrics across multiple processes.

Simplest way to achieve this is to use the built-in collector.

First, run an exporter on your desired port (we use the default bind to localhost and port of 9394):

$ prometheus_exporter

And in your application:

ruby
require 'prometheus_exporter/client'

client = PrometheusExporter::Client.default
gauge = client.register(:gauge, "awesome", "amount of awesome")

gauge.observe(10)
gauge.observe(99, day: "friday")

Then you will get the metrics:

$ curl localhost:9394/metrics
# HELP collector_working Is the master process collector able to collect metrics
# TYPE collector_working gauge
collector_working 1

# HELP awesome amount of awesome
# TYPE awesome gauge
awesome{day="friday"} 99
awesome 10

Custom quantiles for summaries and buckets for histograms can also be passed in.

ruby
require 'prometheus_exporter/client'

client = PrometheusExporter::Client.default
histogram = client.register(:histogram, "api_time", "time to call api", buckets: [0.1, 0.5, 1])

histogram.observe(0.2, api: 'twitter')

Rails integration

You can easily integrate into any Rack application.

In your Gemfile:

ruby
gem 'prometheus_exporter'

In an initializer:

ruby
unless Rails.env.test?
  require 'prometheus_exporter/middleware'

  # This reports stats per request like HTTP status and timings
  Rails.application.middleware.unshift PrometheusExporter::Middleware
end

Ensure you run the exporter in a monitored background process:

$ bundle exec prometheus_exporter

Choosing the style of method patching

By default, prometheus_exporter uses alias_method to instrument methods used by SQL and Redis as it is the fastest approach (see this article). You may desire to add additional instrumentation libraries beyond prometheus_exporter to your app. This can become problematic if these other libraries instead use prepend to instrument methods. To resolve this, you can tell the middleware to instrument using prepend by passing an instrument option like so:

ruby
Rails.application.middleware.unshift PrometheusExporter::Middleware, instrument: :prepend

Metrics collected by Rails integration middleware

Type Name Description
Counter http_requests_total Total HTTP requests from web app
Summary http_request_duration_seconds Time spent in HTTP reqs in seconds
Summary http_request_redis_duration_seconds¹ Time spent in HTTP reqs in Redis, in seconds
Summary http_request_sql_duration_seconds² Time spent in HTTP reqs in SQL in seconds
Summary http_request_queue_duration_seconds³ Time spent queueing the request in load balancer in seconds
Summary http_request_memcache_duration_seconds⁴ Time spent in HTTP reqs in Memcache in seconds

All metrics have a controller and an action label. http_requests_total additionally has a (HTTP response) status label.

To add your own labels to the default metrics, create a subclass of PrometheusExporter::Middleware, override custom_labels, and use it in your initializer.

…

ruby

puma.rb config

require 'prometheus_exporter/instrumentation'

optional check, avoids spinning up and down threads per worker

if !PrometheusExporter::Instrumentation::Puma.started? PrometheusExporter::Instrumentation::Puma.start end


For Puma clustered mode
```ruby
# puma.rb config
after_worker_boot do
  require 'prometheus_exporter/instrumentation'
  # optional check, avoids spinning up and down threads per worker
  if !PrometheusExporter::Instrumentation::Puma.started?
    PrometheusExporter::Instrumentation::Puma.start
  end
end

…

ruby
# e.g. config/initializers/resque.rb
require 'prometheus_exporter/instrumentation'
PrometheusExporter::Instrumentation::Resque.start

…

ruby
# e.g. config/initializers/good_job.rb
require 'prometheus_exporter/instrumentation'
PrometheusExporter::Instrumentation::GoodJob.start

…

bash
prometheus_exporter --unicorn-master /var/run/unicorn.pid --unicorn-listen-address 127.0.0.1:3000

# alternatively, if you're using unix sockets:
prometheus_exporter --unicorn-master /var/run/unicorn.pid --unicorn-listen-address /var/run/unicorn.sock

…

ruby
# person_collector.rb
class PersonCollector  21
      @oldies.observe(1)
    else
      @youngies.observe(1)
    end
  end

  def metrics
    [@oldies, @youngies]
  end
end

Shipping metrics then is done via:

ruby
PrometheusExporter::Client.default.send_json(type: "person", age: 40)

To load the custom collector run:

$ bundle exec prometheus_exporter -a person_collector.rb

Global metrics in a custom type collector

Custom type collectors are the ideal place to collect global metrics, such as user/article counts and connection counts. The custom type collector runs in the collector, which usually runs in the prometheus exporter process.

Out-of-the-box we try to keep the prometheus exporter as lean as possible. We do not load all Rails dependencies, so you won't have access to your models. You can always ensure it is loaded in your custom type collector with:

ruby
unless defined? Rails
  require File.expand_path("../../config/environment", __FILE__)
end

Then you can collect the metrics you need on demand:

ruby
def metrics
  user_count_gauge = PrometheusExporter::Metric::Gauge.new('user_count', 'number of users in the app')
  user_count_gauge.observe User.count
  [user_count_gauge]
end

…

ruby
class MyCustomCollector  "app-server-01" }

counter = PrometheusExporter::Metric::Counter.new("web_requests", "number of web requests")

counter.observe(1, route: 'test/route')
counter.observe

Will result in:

# HELP web_requests number of web requests
# TYPE web_requests counter
ruby_web_requests{hostname="app-server-01",route="test/route"} 1
ruby_web_requests{hostname="app-server-01"} 1

Exporter Process Configuration

When running the process for prometheus_exporter using bin/prometheus_exporter, there are several configurations that can be passed in:

Usage: prometheus_exporter [options]
    -p, --port INTEGER               Port exporter should listen on (default: 9394)
    -b, --bind STRING                IP address exporter should listen on (default: localhost)
    -t, --timeout INTEGER            Timeout in seconds for metrics endpoint (default: 2)
        --prefix METRIC_PREFIX       Prefix to apply to all metrics (default: ruby_)
        --label METRIC_LABEL         Label to apply to all metrics (default: {})
    -c, --collector FILE             (optional) Custom collector to run
    -a, --type-collector FILE        (optional) Custom type collectors to run in main collector
    -v, --verbose
    -g, --histogram                  Use histogram instead of summary for aggregations
        --auth FILE                  (optional) enable basic authentication using a htpasswd FILE
        --realm REALM                (optional) Use REALM for basic authentication (default: "Prometheus Exporter")
        --unicorn-listen-address ADDRESS
                                     (optional) Address where unicorn listens on (unix or TCP address)
        --unicorn-master PID_FILE    (optional) PID file of unicorn master process to monitor unicorn

Example

The following will run the process at

  • Port 8080 (default 9394)
  • Bind to 0.0.0.0 (default localhost)
  • Timeout in 1 second for metrics endpoint (default 2 seconds)
  • Metric prefix as foo_ (default ruby_)
  • Default labels as {environment: "integration", foo: "bar"}
bash
prometheus_exporter -p 8080 \
                    -b 0.0.0.0 \
                    -t 1 \
                    --label '{"environment": "integration", "foo": "bar"}' \
                    --prefix 'foo_'

You can use -b option to bind the prometheus_exporter web server to any IPv4 interface with -b 0.0.0.0, any IPv6 interface with -b ::, or -b ANY to any IPv4/IPv6 interfaces available on your host system.

Enabling Basic Authentication

If you desire authentication on your /metrics route, you can enable basic authentication with the --auth option.

$ prometheus_exporter --auth my-htpasswd-file

Additionally, the --realm option may be used to provide a customized realm for the challenge request.

Notes:

  • You will need to create a htpasswd formatted file before hand which contains one or more user:password entries
  • Only the basic crypt e

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyrubygem

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言