Skip to content

Commit

Permalink
Merge pull request #8 from machadovilaca/add-collector-const-labels
Browse files Browse the repository at this point in the history
Add collector const labels
  • Loading branch information
assafad committed Mar 26, 2024
2 parents 2656097 + ccb9b34 commit 50ee142
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
17 changes: 13 additions & 4 deletions pkg/operatormetrics/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ type Collector struct {
}

type CollectorResult struct {
Metric Metric
Labels []string
Value float64
Metric Metric
Labels []string
ConstLabels map[string]string
Value float64
}

func (c Collector) hash() string {
Expand Down Expand Up @@ -73,11 +74,19 @@ func collectValue(ch chan<- prometheus.Metric, metric Metric, cr CollectorResult
return fmt.Errorf("encountered unsupported type for collector %v", metric.GetType())
}

labels := map[string]string{}
for k, v := range cr.ConstLabels {
labels[k] = v
}
for k, v := range metric.GetOpts().ConstLabels {
labels[k] = v
}

desc := prometheus.NewDesc(
metric.GetOpts().Name,
metric.GetOpts().Help,
metric.GetOpts().labels,
metric.GetOpts().ConstLabels,
labels,
)

cm, err := prometheus.NewConstMetric(desc, mType, cr.Value, cr.Labels...)
Expand Down
31 changes: 31 additions & 0 deletions pkg/operatormetrics/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,36 @@ var _ = Describe("Collector", func() {

Expect(ch).NotTo(Receive())
})

It("should collect metrics with const labels added on collection time", func() {
counter := NewCounter(testCounterOpts)

collector := Collector{
Metrics: []Metric{counter},
CollectCallback: func() []CollectorResult {
return []CollectorResult{
{
Metric: counter,
Labels: nil,
ConstLabels: map[string]string{
"important_info": "xpto",
},
Value: 5,
},
}
},
}

err := RegisterCollector(collector)
Expect(err).NotTo(HaveOccurred())

ch := make(chan prometheus.Metric, 1)
go collector.Collect(ch)

metricCounter := <-ch

Expect(metricCounter.Desc().String()).To(ContainSubstring(testCounterOpts.Name))
Expect(metricCounter.Desc().String()).To(ContainSubstring("constLabels: {important_info=\"xpto\"}"))
})
})
})

0 comments on commit 50ee142

Please sign in to comment.