Skip to content

Instantly share code, notes, and snippets.

@rfratto
Last active February 17, 2021 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfratto/44ba8cb8f8e0bc973e7fd8a1cdcf2e08 to your computer and use it in GitHub Desktop.
Save rfratto/44ba8cb8f8e0bc973e7fd8a1cdcf2e08 to your computer and use it in GitHub Desktop.
One way to do non-global Prometheus metrics in an application
package main
import (
"os"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/common/expfmt"
)
// Adder adds numbers.
type Adder struct {
addsTotal prometheus.Counter
}
// NewAdder instantiates an Adder and registers metrics to the given
// reg. reg may be nil.
func NewAdder(reg prometheus.Registerer) *Adder {
// If other structs need access to addsTotal, you'd instead want to create an
// AdderMetrics struct that holds metrics and pass that around instead:
//
// type AdderMetrics struct {
// addsTotal prometheus.Counter
// }
//
// func NewAdderMetrics(reg prometheus.Registerer) *AdderMetrics {
// return &AdderMetrics{
// addsTotal: promauto.With(reg).NewCounter(prometheus.CounterOpts{
// Name: "adder_adds_total",
// Help: "Total amount of times Adder.Add was invoked",
// }),
// }
// }
//
return &Adder{
addsTotal: promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "adder_adds_total",
Help: "Total amount of times Adder.Add was invoked",
}),
}
}
// Add adds two values.
func (a *Adder) Add(lhs, rhs int) int {
a.addsTotal.Inc()
return lhs + rhs
}
// Output:
//
// # HELP adder_adds_total Total amount of times Adder.Add was invoked
// # TYPE adder_adds_total counter
// adder_adds_total 100
func main() {
// You could also use prometheus.DefaultRegistry/DefaultGatherer here if
// you wanted to keep default metrics (like the Go runtime metrics).
reg := prometheus.NewPedanticRegistry()
adder := NewAdder(reg)
for i := 0; i < 100; i++ {
adder.Add(i, i)
}
printMetrics(reg)
}
func printMetrics(gatherer prometheus.Gatherer) {
families, err := gatherer.Gather()
if err != nil {
panic(err)
}
enc := expfmt.NewEncoder(os.Stdout, expfmt.FmtText)
for _, f := range families {
if err := enc.Encode(f); err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment