Tutorial: Emit custom metrics from a Ruby application  using Prometheus Client

Tutorial: Emit custom metrics from a Ruby application using Prometheus Client

In this post, we will use the Prometheus client to emit custom metrics from the Ruby application

Step 1: Install the Prometheus Client

First, add the following line to your application's Gemfile:

gem 'prometheus-client'

And then execute:

$ bundle install

Step 2: Initialize the Metrics

Next, you need to initialize your metrics. These are the metrics you want to track. You can do this in the file where you want to track the metrics, or ideally in an initializer if you are using a framework like Rails.

Here are some examples of how to initialize different types of metrics:

require 'prometheus/client'

prometheus = Prometheus::Client.registry

# Counter
http_requests_total = Prometheus::Client::Counter.new(:http_requests_total, "A counter of HTTP requests made")

# Summary
read_latency = Prometheus::Client::Summary.new(:ruby_http_request_duration_seconds, "A summary of the HTTP request duration in seconds")

# Register Metrics
prometheus.register(http_requests_total)
prometheus.register(read_latency)

Step 3: Update Metrics

In the appropriate place in your code, you can update these metrics. For instance:

http_requests_total.increment
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# some HTTP request code here
elapsed_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
read_latency.observe(elapsed_time)

Step 4: Expose Metrics

Prometheus needs to scrape these metrics from an endpoint in your application. You can use the prometheus/middleware/exporter middleware to automatically expose metrics on /metrics.

If you are using Rails, you would add this to your config.ru:

require 'prometheus/middleware/exporter'

use Prometheus::Middleware::Exporter

Step 5: Configure Prometheus

Finally, you will need to configure your Prometheus instance to scrape metrics from your Ruby application. Add the following to your prometheus.yml configuration file:

scrape_configs:
  - job_name: 'ruby_app'
    scrape_interval: 5s
    static_configs:
      - targets: ['<hostname>:<port>']

Replace <hostname>:<port> with your Ruby application's hostname and port.

Now, your Ruby application is set up to emit custom metrics and Prometheus is configured to scrape them. You can view these metrics in the Prometheus dashboard, or use them to create custom alerts or Grafana dashboards.

Read more about the difference between OpenTelemetry vs Prometheus