github.com/grafana/pyroscope@v1.18.0/pkg/util/prometheus.go (about) 1 package util 2 3 import ( 4 "errors" 5 6 "github.com/prometheus/client_golang/prometheus" 7 ) 8 9 // RegisterOrGet registers the collector c with the provided registerer. 10 // If the registerer is nil, the collector is returned without registration. 11 // If the collector is already registered, the existing collector is returned. 12 func RegisterOrGet[T prometheus.Collector](reg prometheus.Registerer, c T) T { 13 if reg == nil { 14 return c 15 } 16 err := reg.Register(c) 17 if err != nil { 18 var already prometheus.AlreadyRegisteredError 19 ok := errors.As(err, &already) 20 if ok { 21 return already.ExistingCollector.(T) 22 } 23 panic(err) 24 } 25 return c 26 } 27 28 func Register(reg prometheus.Registerer, collectors ...prometheus.Collector) { 29 if reg == nil { 30 return 31 } 32 for _, collector := range collectors { 33 err := reg.Register(collector) 34 if err != nil { 35 var alreadyRegisteredError prometheus.AlreadyRegisteredError 36 ok := errors.As(err, &alreadyRegisteredError) 37 if !ok { 38 panic(err) 39 } 40 } 41 } 42 }