client_golang icon indicating copy to clipboard operation
client_golang copied to clipboard

Type-safe labels support?

Open amberpixels opened this issue 1 year ago • 1 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: https://github.com/prometheus/client_golang/pull/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()

amberpixels avatar Aug 28 '24 13:08 amberpixels

Hello 👋 Looks like there was no activity on this issue for the last 3 months. Do you mind updating us on the status? Is this still reproducible or needed? If yes, just comment on this PR or push a commit. Thanks! 🤗 If there will be no activity in the next 4 weeks, this issue will be closed (we can always reopen an issue if we need!).

stale[bot] avatar Jul 19 '25 06:07 stale[bot]