Get prometheus metric properties

Viewed 44

Assume I have a histogram metric:

requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
    Name:    "example_request_duration_seconds",
    Help:    "Histogram for the runtime of a simple example function.",
    Buckets: prometheus.LinearBuckets(0.01, 0.01, 10),
}, []string{"label1"})

I would like to access properties like Help, Labels, Buckets, ConstLabels, Objectives, MaxAge, etc.. How can I do that?

I am basically trying to write unit tests to verify these properties with expected ones.

1 Answers

Because the Desc(ription) type has all of its fields unexported, you have to take a detour through the lower-level protobuf definitions, using a Registry:

package main

import (
    "testing"

    "github.com/prometheus/client_golang/prometheus"
    dto "github.com/prometheus/client_model/go"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

var requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
    Name:    "example_request_duration_seconds",
    Help:    "Histogram for the runtime of a simple example function.",
    Buckets: prometheus.LinearBuckets(0.01, 0.01, 10),
}, []string{"label1"})

func TestMetrics(t *testing.T) {
    reg := prometheus.NewPedanticRegistry()
    err := reg.Register(requestDuration)
    require.NoError(t, err)

    // The built-in collectors must observe at least one values before they
    // are exported.
    //
    // This With call implicitly verifies that your labels are as expected.
    // If your program setup initializes metrics you can omit this and verify
    // labels directly as demonstrated below. Initializing metrics is best
    // practice; see
    // https://prometheus.io/docs/practices/instrumentation/#avoid-missing-metrics).
    requestDuration.With(prometheus.Labels{"label1": "foo"}).Observe(0)

    metrics, err := reg.Gather()
    require.NoError(t, err)
    require.Len(t, metrics, 1)

    assert.Equal(t, dto.MetricType_HISTOGRAM, metrics[0].GetType())
    assert.Equal(t, "example_request_duration_seconds", metrics[0].GetName())
    assert.Equal(t, "Histogram for the runtime of a simple example function.", metrics[0].GetHelp())

    // Label verification only required if Observe call above can be omitted.
    labels := metrics[0].GetMetric()[0].GetLabel()
    require.Len(t, labels, 1)
    assert.Equal(t, "label1", labels[0].GetName())

    buckets := metrics[0].GetMetric()[0].GetHistogram().GetBucket()
    require.Len(t, buckets, 10)
    assert.InDelta(t, 0.01, buckets[0].GetUpperBound(), 1e-6)
    assert.InDelta(t, 0.02, buckets[1].GetUpperBound(), 1e-6)
    // ...
    assert.InDelta(t, 0.09, buckets[8].GetUpperBound(), 1e-6)
    assert.InDelta(t, 0.10, buckets[9].GetUpperBound(), 1e-6)
}
Related