在默认的Golang Prometheus指标中添加标签

6

我目前正在使用 github.com/prometheus/client_golang 作为获取我的Golang应用程序指标的端点。它提供了许多默认数据集,例如:

go_gc_duration_seconds{quantile="0"} 0
go_gc_duration_seconds{quantile="0.25"} 0
go_gc_duration_seconds{quantile="0.5"} 0
go_gc_duration_seconds{quantile="0.75"} 0
go_gc_duration_seconds{quantile="1"} 0
go_gc_duration_seconds_sum 0
go_gc_duration_seconds_count 0
# HELP go_goroutines Number of goroutines that currently exist.
# TYPE go_goroutines gauge
go_goroutines 10
# HELP go_info Information about the Go environment.
# TYPE go_info gauge
go_info{version="go1.13.10"} 1

我似乎找不到库中添加标签到这些数据集的任何功能。因为我将在同一台机器上运行许多这些应用程序,所以我需要添加标签来区分数据点。在client_golang库中有没有这样做的方法呢?

3个回答

1
你需要一个自定义的注册表,它知道如何向指标添加自定义标签 :)
type customMetricsRegistry struct {
    *prometheus.Registry
    customLabels []*io_prometheus_client.LabelPair
}

func NewCustomMetricsRegistry(labels map[string]string) *customMetricsRegistry {
    c := &customMetricsRegistry{
        Registry: prometheus.NewRegistry(),
    }

    for k, v := range labels {
        c.customLabels = append(c.customLabels, &io_prometheus_client.LabelPair{
            Name:  &k,
            Value: &v,
        })
    }

    return c
}

func (g *customMetricsRegistry) Gather() ([]*io_prometheus_client.MetricFamily, error) {
    metricFamilies, err := g.Registry.Gather()

    for _, metricFamily := range metricFamilies {
        metrics := metricFamily.Metric
        for _, metric := range metrics {
            metric.Label = append(metric.Label, g.customLabels...)
        }
    }

    return metricFamilies, err
}

然后像这样使用它:
metricsRegistry := NewCustomMetricsRegistry(map[string]string{"hello": "world"})
metricsRegistry.MustRegister(collectors.NewGoCollector())

1
每个应用程序都应该作为一个单独的作业/实例被Prometheus抓取。它将添加“job”标签和“instance”标签,这也可以区分不同的进程(并允许您区分相同作业的多个实例)。
有关更多详细信息,请参见https://prometheus.io/docs/concepts/jobs_instances/#automatically-generated-labels-and-time-series
您还可以使用重新标记规则根据发现应用程序的方式添加其他标签。如果您使用静态配置(https://prometheus.io/docs/prometheus/latest/configuration/configuration/#static_config),则可以在该配置中添加额外的区分标签。同样,对于file_sd_confighttps://prometheus.io/docs/prometheus/latest/configuration/configuration/#file_sd_config

-1

有一个选项可以添加常量标签。例如:

var (
    labels = map[string]string{"application": "foobar"}

    // Status Metrics
    StateCalls = prometheus.NewCounter(prometheus.CounterOpts{
        Name:        "state_calls",
        Help:        "",
        ConstLabels: labels,
    })
)

你正在创建一个新的指标,但OP想知道如何修改现有的指标。 - Maria Ines Parnisari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接