Skip to content

Commit

Permalink
metrics: Allow metrics to be registered multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
mitjat committed Aug 11, 2023
1 parent 00c57d6 commit f47dc6f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions metrics/database.go
Expand Up @@ -45,8 +45,8 @@ func NewDefaultDatabaseMetrics(pkg string) DatabaseMetrics {
databaseLatencyLabels,
),
}
prometheus.MustRegister(metrics.DatabaseOperations)
prometheus.MustRegister(metrics.DatabaseLatencies)
metrics.DatabaseOperations = registerOnce(metrics.DatabaseOperations).(*prometheus.CounterVec)
metrics.DatabaseLatencies = registerOnce(metrics.DatabaseLatencies).(*prometheus.HistogramVec)
return metrics
}

Expand Down
File renamed without changes.
23 changes: 23 additions & 0 deletions metrics/util.go
@@ -0,0 +1,23 @@
package metrics

import (
"errors"

"github.com/prometheus/client_golang/prometheus"
)

// Registers the collector with Prometheus. If an identical collector is already
// registered, returns the existing collector, otherwise returns the provided collector.
// Panics if the collector cannot be registered.
func registerOnce(collector prometheus.Collector) prometheus.Collector {
if err := prometheus.Register(collector); err != nil {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
// Use the old collector from now on.
return are.ExistingCollector
}
// Something else went wrong.
panic(err)
}
return collector
}

0 comments on commit f47dc6f

Please sign in to comment.