簡體   English   中英

獲取普羅米修斯指標屬性

[英]Get prometheus metric properties

假設我有一個直方圖指標:

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"})

我想訪問 Help、Labels、Buckets、ConstLabels、Objectives、MaxAge 等屬性。我該怎么做?

我基本上是在嘗試編寫單元測試來驗證這些屬性是否符合預期。

因為Desc(ription) 類型的所有字段都未導出,所以您必須使用注冊表繞過較低級別的 protobuf 定義:

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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM