为 Prometheus 埋点 Go 应用程序

Prometheus 提供了一个官方的 Go 客户端库 ,你可以使用它来为 Go 应用程序埋点。在本指南中,我们将创建一个简单的 Go 应用程序,通过 HTTP 暴露 Prometheus 指标。

注意如需完整的 API 文档,请参阅 Prometheus 各个 Go 库的 GoDoc 

安装

你可以使用 go get 安装本指南所需的 prometheuspromautopromhttp 库:

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promauto
go get github.com/prometheus/client_golang/prometheus/promhttp

Go 指标暴露的工作原理

要在 Go 应用程序中暴露 Prometheus 指标,你需要提供一个 /metrics HTTP 端点。你可以使用 prometheus/promhttp 库的 HTTP Handler 作为处理函数。

例如,下面这个极简应用程序将通过 https://:2112/metrics 暴露 Go 应用程序的默认指标:

package main

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	reg := prometheus.NewRegistry()
	reg.MustRegister(
		collectors.NewGoCollector(),
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
	)
	http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
	http.ListenAndServe(":2112", nil)
}

启动应用程序

go run main.go

访问指标

curl https://:2112/metrics

添加自定义指标

上文中的应用程序仅暴露了默认的 Go 指标。你还可以注册自己的自定义应用程序指标。此示例程序暴露了一个 myapp_processed_ops_total 计数器 (counter),用于统计迄今为止处理的操作数量。每隔 2 秒,该计数器就会加一。

package main

import (
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

type metrics struct {
	opsProcessed prometheus.Counter
}

func newMetrics(reg prometheus.Registerer) *metrics {
	m := &metrics{
		opsProcessed: promauto.With(reg).NewCounter(prometheus.CounterOpts{
			Name: "myapp_processed_ops_total",
			Help: "The total number of processed events",
		}),
	}
	return m
}

func recordMetrics(m *metrics) {
	go func() {
		for {
			m.opsProcessed.Inc()
			time.Sleep(2 * time.Second)
		}
	}()
}

func main() {
	reg := prometheus.NewRegistry()
	m := newMetrics(reg)
	recordMetrics(m)

	http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
	http.ListenAndServe(":2112", nil)
}

运行应用程序

go run main.go

访问指标

curl https://:2112/metrics

在指标输出中,你将看到 myapp_processed_ops_total 计数器的帮助文本、类型信息和当前值:

# HELP myapp_processed_ops_total The total number of processed events
# TYPE myapp_processed_ops_total counter
myapp_processed_ops_total 5

你可以配置一个本地运行的 Prometheus 实例来抓取该程序的指标。以下是一个 prometheus.yml 配置示例:

scrape_configs:
- job_name: myapp
  scrape_interval: 10s
  static_configs:
  - targets:
    - localhost:2112

Go 客户端的其他特性

在本指南中,我们仅介绍了 Prometheus Go 客户端库中一小部分功能。你还可以暴露其他指标类型,例如 仪表盘 (gauges) 直方图 (histograms) ,使用 非全局注册表 ,通过函数将 指标推送到  Prometheus PushGateways,桥接 Prometheus 和 Graphite  等等。

总结

在本指南中,你创建了两个暴露 Prometheus 指标的示例 Go 应用程序——一个仅暴露默认 Go 指标,另一个还暴露了自定义 Prometheus 计数器——并配置了一个 Prometheus 实例从这些程序抓取指标。

本页内容