为 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 计数器,用于统计到目前为止已处理的操作数量。每 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 客户端库中可用的一小部分功能。您还可以暴露其他指标类型,例如计量器 直方图 非全局注册表 、用于将指标推送到  Prometheus PushGateways 的功能,以及连接 Prometheus 和 Graphite  等更多功能。

总结

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

本页内容