簡介
本篇為 Prometheus GO client package 的用法筆記
metric endpoint
1http.Handle("/metrics", promhttp.Handler())
自定義 metric
加上自定義 metric,文件建議用 MustRegister()確保 collector 和 metric 一致,如果不相容或不一致,例如有相同 name 的 collector,會在註冊時就引發 panic,不會等到實際抓 metric 才 panic
1import (
2 "net/http"
3
4 "github.com/prometheus/client_golang/prometheus"
5 "github.com/prometheus/client_golang/prometheus/collectors"
6 "github.com/prometheus/client_golang/prometheus/promhttp"
7)
8
9var (
10 RequestsTotal = promauto.NewCounterVec(
11 prometheus.CounterOpts{
12 Name: "http_requests_total",
13 Help: "Tracks the number of HTTP requests.",
14 }, []string{"method", "code", "uri"},
15 )
16 RequestDuration = promauto.NewHistogramVec(
17 prometheus.HistogramOpts{
18 Name: "http_request_duration_seconds",
19 Help: "Tracks the latencies for HTTP requests.",
20 Buckets: prometheus.ExponentialBuckets(0.1, 5, 5),
21 },
22 []string{"uri"},
23 )
24)
25
26func main() {
27 registry := prometheus.NewRegistry()
28 registry.MustRegister(
29 collectors.NewGoCollector(),
30 collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
31 helper.RequestDuration,
32 helper.RequestsTotal,
33 )
34
35 http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
36 if err := http.ListenAndServe(":8080", nil); err != nil {
37 panic(err)
38 }
39}
Collector
常規的 Counter、Gauge、Histogram、Summary
metric 新增 value(還有其他方式見文件)
1counter.Inc()
2gauge.Inc()
3gauge.Dec()
4histogram.Observe(1.23)
5summary.Observe(1.23)
還各自有向量 Vec 版本,可以定義一組一樣的資料但不同的 label
範例
1requestsTotal := promauto.NewCounterVec(
2 prometheus.CounterOpts{
3 Name: "http_requests_total",
4 Help: "Tracks the number of HTTP requests.",
5 }, []string{"method", "code", "uri"},
6)
7requestsTotal.WithLabelValues("POST", 200, "user").Inc()
histogram bucket
1func ExponentialBuckets(start, factor float64, count int) []float64
start 為第一個上邊界,每個 bucket 邊界為前一個邊界乘上 factor,共有 count + 1 個 bucket
例 ExponentialBuckets(0.1, 5, 5),其 6 個 bucket 的 le 分別為
- 0.1
- 0.5
- 2.5
- 12.5
- 62.5
- +Inf