I have a function, which handles some events:
func (h *Handler) OnEvent(e *Event) {
log.Printf("%s, %s", e.Label, e.Type)
}
I want to create a Prometheus counter which will tick on each event. There are two caveats:
OnEvent
runs in goroutinee.Label
ande.Type
could be different in different periods of time, so I can't pre-register all counters on startup.
My main question is how to register Prometheus counters safely?
If I do this inside OnEvent
func (h *Handler) OnEvent(e *Event) {
log.Printf("%s, %s", e.Label, e.Type)
c := prometheus.NewCounter(prometheus.CounterOpts{
Name: "example",
Help: "Example.",
ConstLabels: map[string]string{
"label": e.Label,
"type": e.Type,
},
})
prometheus.MustRegister(c)
c.Inc()
pusher := getPusher()
if err := pusher. //push new counter value to Pushgateway
Collector(c).
Push(); err != nil {
fmt.Println(err)
}
I will get panic on MustRegister
on 2nd event with identical label and type.
There is no way to "retrieve" an existing counter, so I want to ask, how should I register all counters and update them.
Example: