Class: Labkit::Metrics::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/labkit/metrics/registry.rb

Overview

A thin wrapper around Prometheus::Client::Registry. It provides a thread-safe way to register metrics with the Prometheus registry.

Constant Summary collapse

INIT_REGISTRY_MUTEX =
Mutex.new
REGISTER_MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.get(metric_name) ⇒ Prometheus::Client::Metric?

Returns the metric for the given name from the Prometheus registry.

Parameters:

  • metric_name (Symbol, String)

    The name of the metric

Returns:

  • (Prometheus::Client::Metric, nil)

    The registered metric or nil if it does not exist



50
51
52
# File 'lib/labkit/metrics/registry.rb', line 50

def get(metric_name)
  wrapped_registry.get(metric_name)
end

.reset!Object

Cleans up the Prometheus registry and resets it to a new state.



38
39
40
41
42
43
44
# File 'lib/labkit/metrics/registry.rb', line 38

def reset!
  INIT_REGISTRY_MUTEX.synchronize do
    Prometheus::Client.cleanup!
    Prometheus::Client.reset!
    @registry = nil
  end
end

.safe_register(metric_type, name, *args) ⇒ Prometheus::Client::Metric

Registers a metric with the Prometheus registry in a thread-safe manner. If the metric already exists, it returns the existing metric. If the metric does not exist, it creates a new one. Each metric-name is only registered once for a type (counter, gauge, histogram, summary), even if multiple threads attempt to register the same metric simultaneously.

Examples:

# Register a counter
counter = Registry.safe_register(:counter, :http_requests_total, 'Total HTTP requests')

Parameters:

  • metric_type (Symbol)

    The type of metric to register (:counter, :gauge, :histogram, :summary)

  • name (Symbol, String)

    The name of the metric

  • args (Array)

    Additional arguments to pass to the metric constructor

Returns:

  • (Prometheus::Client::Metric)

    The registered metric

Raises:



31
32
33
34
35
# File 'lib/labkit/metrics/registry.rb', line 31

def safe_register(metric_type, name, *args)
  REGISTER_MUTEX.synchronize do
    get(name) || wrapped_registry.method(metric_type).call(name, *args)
  end
end