Sha256: 0ab4bd5898a684535a56a5f6df9770831f7acc86b0b8c2f42038521361dac116

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

require 'prometheus/client'
require 'prometheus/client/formats/text'

##
# Middleware responsible to configure prometheus
# defining metrics and an endpoint to access them.
class PrometheusMiddleware
  attr_accessor :request_duration_milliseconds, :request_count, :response_count

  def configure_prometheus(prometheus_registry, configurations, macaw)
    return nil unless prometheus_registry

    @request_duration_milliseconds = Prometheus::Client::Histogram.new(
      :request_duration_milliseconds,
      docstring: 'The duration of each request in milliseconds',
      labels: [:endpoint],
      buckets: (100..1000).step(100).to_a + (2000..10_000).step(1000).to_a
    )

    @request_count = Prometheus::Client::Counter.new(
      :request_count,
      docstring: 'The total number of requests received',
      labels: [:endpoint]
    )

    @response_count = Prometheus::Client::Counter.new(
      :response_count,
      docstring: 'The total number of responses sent',
      labels: %i[endpoint status]
    )

    prometheus_registry.register(@request_duration_milliseconds)
    prometheus_registry.register(@request_count)
    prometheus_registry.register(@response_count)
    prometheus_endpoint(prometheus_registry, configurations, macaw)
  end

  private

  def prometheus_endpoint(prometheus_registry, configurations, macaw)
    endpoint = configurations['macaw']['prometheus']['endpoint'] || '/metrics'
    macaw.get(endpoint) do |_context|
      [Prometheus::Client::Formats::Text.marshal(prometheus_registry), 200, { 'Content-Type' => 'plaintext' }]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
macaw_framework-1.3.21 lib/macaw_framework/middlewares/prometheus_middleware.rb
macaw_framework-1.3.1 lib/macaw_framework/middlewares/prometheus_middleware.rb