Check for custom labels in the generic exporter (#48)

approved
#1
Check for custom labels in the generic exporter (#48)

Merge them with the sent over keys, giving preference for anything
inside of keys over custom_labels

From 890cbcf4a993a84fa72bf2dee58f59d79fc831b2 Mon Sep 17 00:00:00 2001
From: Eric Oestrich <eric@oestrich.org>
Date: Wed, 5 Dec 2018 23:57:22 -0500
Subject: [PATCH] Check for custom labels in the generic exporter (#48)

Merge them with the sent over keys, giving preference for anything
inside of `keys` over `custom_labels`

diff --git a/lib/prometheus_exporter/server/collector.rb b/lib/prometheus_exporter/server/collector.rb
index 37b3b85..7a75a24 100644
--- a/lib/prometheus_exporter/server/collector.rb
+++ b/lib/prometheus_exporter/server/collector.rb
@@ -48,13 +48,19 @@ module PrometheusExporter::Server
           if !metric
             metric = register_metric_unsafe(obj)
           end
+
+          keys = obj["keys"] || {}
+          if obj["custom_labels"]
+            keys = obj["custom_labels"].merge(keys)
+          end
+
           case obj["prometheus_exporter_action"]
           when 'increment'
-            metric.increment(obj["keys"], obj["value"])
+            metric.increment(keys, obj["value"])
           when 'decrement'
-            metric.decrement(obj["keys"], obj["value"])
+            metric.decrement(keys, obj["value"])
           else
-            metric.observe(obj["value"], obj["keys"])
+            metric.observe(obj["value"], keys)
           end
         end
       end
diff --git a/test/server/collector_test.rb b/test/server/collector_test.rb
index dc161b1..ac811da 100644
--- a/test/server/collector_test.rb
+++ b/test/server/collector_test.rb
@@ -146,6 +146,32 @@ class PrometheusCollectorTest < Minitest::Test
     assert(result.include?('sidekiq_jobs_total{job_name="WrappedClass",service="service1"} 1'), "has sidekiq working job from ActiveJob")
   end
 
+  def test_it_merges_custom_labels_for_generic_metrics
+    name = 'test_name'
+    help = 'test_help'
+    collector = PrometheusExporter::Server::Collector.new
+    metric = PrometheusExporter::Metric::Gauge.new(name, help)
+    collector.register_metric(metric)
+    json = {
+      type: :gauge,
+      help: help,
+      name: name,
+      custom_labels: { host: "example.com" },
+      keys: { key1: 'test1' },
+      value: 5
+    }.to_json
+
+    collector.process(json)
+
+    text = <<~TXT
+      # HELP test_name test_help
+      # TYPE test_name gauge
+      test_name{host="example.com",key1="test1"} 5
+    TXT
+
+    assert_equal(text, collector.prometheus_metrics_text)
+  end
+
   def test_it_can_collect_process_metrics
     # make some mini racer data
     ctx = MiniRacer::Context.new

GitHub

Approved #2