Gauge 中的动态普罗米修斯标签

ken*_*tor 6 go prometheus

我想知道是否/如何添加动态标签。我不知道要添加到仪表值中的标签的键或数量。

我试过的

labelsContainers = []string{"node", "container", "pod", "qos", "namespace", "nodepool"}

// Requested resources
requestedContainerCPUCoresGauge = prometheus.NewGaugeVec(
    prometheus.GaugeOpts{
        Namespace: namespace,
        Subsystem: "pod_container_resource_requests",
        Name:      "cpu_cores",
        Help:      "Requested CPU cores in Kubernetes configuration",
    },
    labelsContainers)

for _, containerMetric := range containerMetrics {
    containerLabels := prometheus.Labels{
        "node":      containerMetric.Node,
        "container": containerMetric.Container,
        "qos":       containerMetric.Qos,
        "pod":       containerMetric.Pod,
        "namespace": containerMetric.Namespace,
    }

    for key, value := range containerMetric.NodeLabels {
        containerLabels[key] = value
    }

    requestedContainerCPUCoresGauge.With(containerLabels).Set(containerMetric.RequestedCPUCores)
    requestedContainerRAMBytesGauge.With(containerLabels).Set(containerMetric.RequestedMemoryBytes)
}
Run Code Online (Sandbox Code Playgroud)

问题

这引发了恐慌。我认为这是因为舞会客户期望在labelsContainers中定义的那些标签并且不允许进一步的标签。如何创建允许附加(未知)标签的仪表?

val*_*ala 1

虽然github.com/prometheus/client_golang库没有提供在指标中指定动态标签的简单方法,但可以使用github.com/VictoriaMetrics/metrics库通过函数 +构建动态标签的GetOrCreate*()常用方法轻松实现此任务。fmt.Sprintf()例如:

import (
        "fmt"
        "sort"
        "strings"

        "github.com/VictoriaMetrics/metrics"
)

// UpdateMetric updates metric `name{labels}` to the given value.
func UpdateMetric(name string, labels map[string]string, value float64) {
        // Construct `metric{labels}`
        var labelValues []string
        for k, v := range labels {
                labelValues = append(labelValues, fmt.Sprintf("%s=%q", k, v))
        }
        sort.Strings(labelValues)
        metricName := fmt.Sprintf("%s{%s}", name, strings.Join(labelValues, ","))

        // Update the counter
        metrics.GetOrCreateFloatCounter(metricName).Set(value)
}
Run Code Online (Sandbox Code Playgroud)