prometheus/client_golang

Type-safe labels support?

amberpixels opened this issue · 0 comments

Context
Currently when using a metric we can provide labels either with an ordered string list, or via prometheus.Labels map. Both seems to be very dangerous: chance of misorder, misspell, extra/missing values. Also it's not convenient, that you do not know which labels you can use until you reach the code of metric creation.

It's especially dangerous when using promauto as it fails on every issue with label.

Solution
As modern Go language has Generics support we can use it to make a strongly-typed labels support.

I have a draft PR pushed already:
#1598

PR's description contains several example: single-label metric, multi-label metric, promauto-combined support, etc.

Here's example of using multi-labeled metric:

      // Registering strongly-type label:

      type MyCounterLabels struct {
		promsafe.StructLabelProvider
		EventType string
		Success   bool
		Position  uint8 // yes, it's a number, but be careful with high-cardinality labels

		ShouldNotBeUsed string `promsafe:"-"`
	}

	c := promsafe.NewCounterVecT[MyCounterLabels](prometheus.CounterOpts{
		Name: "items_counted",
	})


	// Using counter with strongly typed labels:
        // It only allows you to use &MyCounterLabels here
       c.With(MyCounterLabels{
		EventType: "reservation", Success: true, Position: 1,
	}).Inc()