Skip to content

Commit

Permalink
Fix NPE when configuring global Prometheus labels
Browse files Browse the repository at this point in the history
  • Loading branch information
bluekeyes committed Aug 11, 2023
1 parent b0cabda commit f5e077f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions appmetrics/emitter/prometheus/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,13 @@ func (c *Collector) descFromName(name string, help string) func(string) *prometh
// labelsFromName extracts the labels from a metric name and returns the
// sanitized base name and the sanitized labels.
func labelsFromName(name string) (string, prometheus.Labels) {
labels := make(prometheus.Labels)

start := strings.IndexRune(name, '[')
if start < 0 || name[len(name)-1] != ']' {
return sanitizeName(name), nil
return sanitizeName(name), labels
}

labels := make(prometheus.Labels)
labelPairs := strings.Split(name[start+1:len(name)-1], ",")
for _, pair := range labelPairs {
key, value, ok := strings.Cut(strings.TrimSpace(pair), ":")
Expand Down
5 changes: 5 additions & 0 deletions appmetrics/emitter/prometheus/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,20 @@ timer_seconds_count 0

counterA := metrics.NewRegisteredCounter("counter[subsystem:a,role:server]", r)
counterB := metrics.NewRegisteredCounter("counter[subsystem:b,role:server]", r)
counterC := metrics.NewRegisteredCounter("unlabeled_counter", r)

counterA.Inc(1)
counterB.Inc(2)
counterC.Inc(3)

expected := `
# HELP counter metrics.Counter
# TYPE counter untyped
counter{role="server",subsystem="a",test="labels"} 1
counter{role="server",subsystem="b",test="labels"} 2
# HELP unlabeled_counter metrics.Counter
# TYPE unlabeled_counter untyped
unlabeled_counter{test="labels"} 3
`

if err := testutil.CollectAndCompare(c, strings.NewReader(expected)); err != nil {
Expand Down

0 comments on commit f5e077f

Please sign in to comment.