Register custom collectors¶
Beyond the built-in Go/process/build-info collectors, you will want to expose your own application metrics — cache sizes, queue depths, work counters. There are two ways.
WithCollectors — a fixed set¶
Pass collectors at construction:
cacheSize := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "myapp_cache_entries",
Help: "Number of entries in the analysis cache.",
})
metrics.Register(mux,
metrics.WithMiddleware(authMiddleware),
metrics.WithCollectors(cacheSize),
)
// update it as your app runs
cacheSize.Set(float64(cache.Len()))
WithRegistry — you own the registry¶
Supply your own *prometheus.Registry and register whatever you like, whenever you
like (including dynamically). transport-metrics adds the runtime/process/build-info
collectors to it and serves it:
reg := prometheus.NewRegistry()
reg.MustRegister(myCounter, myHistogram)
m, err := metrics.New(metrics.WithRegistry(reg))
if err != nil { return err }
m.MountOn(mux)
// later, register more
reg.MustRegister(anotherCollector)
m.Registry() also returns the registry after construction, so you can register
additional collectors without holding a separate reference.
Build labels on your own metrics¶
m.BuildInfo() returns the resolved version/revision/Go version, handy for stamping
the same labels onto your metrics as ConstLabels so everything filters by build
consistently:
bi := m.BuildInfo()
c := prometheus.NewCounter(prometheus.CounterOpts{
Name: "myapp_jobs_total",
Help: "Jobs processed.",
ConstLabels: prometheus.Labels{"version": bi.Version},
})
A note on cardinality¶
Every label you add multiplies series. Keep label values bounded — never put a user id, request id, or raw path in a label. See Cardinality safety.