[英]How to push metrics to prometheus using client_golang?
我還沒有找到一些在 prometheus 中使用 Gauge、Counter 和 Histogram 的好例子。 對此的任何幫助都可以。 我嘗試使用文檔,但無法成功創建工作應用程序。
我找到了這個
`
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
)
var (
cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "cpu_temperature_celsius",
Help: "Current temperature of the CPU.",
})
hdFailures = prometheus.NewCounter(prometheus.CounterOpts{
Name: "hd_errors_total",
Help: "Number of hard-disk errors.",
})
)
func init() {
prometheus.MustRegister(cpuTemp)
prometheus.MustRegister(hdFailures)
}
func main() {
cpuTemp.Set(65.3)
hdFailures.Inc()
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(":8080", nil)
}
`
這可能對某些人有用。
Prometheus 是一個基於拉的系統,如果你想要基於推送的監控,你需要使用某種網關。 一個最小的例子(實際上沒有做任何有用的事情,比如啟動一個 HTTP 監聽器,或者實際上對一個指標做任何事情)如下:
import (
"github.com/prometheus/client_golang/prometheus"
"net/http"
)
var responseMetric = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "request_duration_milliseconds",
Help: "Request latency distribution",
Buckets: prometheus.ExponentialBuckets(10.0, 1.13, 40),
})
func main() {
prometheus.MustRegister(responseMetric)
http.Handle("/metrics", prometheus.Handler())
// Any other setup, then an http.ListenAndServe here
}
然后,您需要配置 Prometheus 來抓取二進制文件提供的/metrics
頁面。
您可以從prometheus/client_golang 中找到示例。 為了讓您開始,您只需獲取以下軟件包:
$ go get github.com/prometheus/client_golang/prometheus
$ go get github.com/prometheus/client_golang/prometheus/push
您可以通過設置正確的 pushgateway 地址來運行以下示例,在此示例中為http://localhost:9091/ :
package main
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
)
func ExamplePusher_Push() {
completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_backup_last_completion_timestamp_seconds",
Help: "The timestamp of the last successful completion of a DB backup.",
})
completionTime.SetToCurrentTime()
if err := push.New("http://localhost:9091/", "db_backup").
Collector(completionTime).
Grouping("db", "customers").
Push(); err != nil {
fmt.Println("Could not push completion time to Pushgateway:", err)
}
}
func main() {
ExamplePusher_Push()
}
運行你的腳本:
$ go run pushExample.go
運行代碼后,您應該會在網關 ( http://localhost:9091/ ) 上看到指標。 界面如下所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.