為 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 例項來從這些應用程式抓取指標。

本頁內容