用 Prometheus 監控 Go HTTP 服務
公開 Go 執行階段指標,透過 promhttp 依路由記錄請求數、處理中請求數與延遲,附擷取設定和 PromQL 範例。
訂單 API 對 /orders/123 傳回 200,對 /orders/missing 傳回 404。這兩筆請求都走同一條路由。直接把網址當成標籤會依訂單 ID 切出不同的時間序列,反而不容易看出整條路由是否變慢,或錯誤是否變多。
本文用 client_golang 為 Go HTTP 處理器加上量測,並透過 /metrics 讓 Prometheus 擷取資料。先確認 Go 執行階段的指標,再依路由記錄請求數、處理中的請求數與處理時間。
先公開 Go 的預設指標
此範例固定的客戶端版本需要 Go 1.23 或更新版本。在空目錄初始化模組,再安裝客戶端程式庫。
go mod init example.com/go-metrics
go get github.com/prometheus/client_golang/prometheus/promhttp@v1.23.2
把以下程式存成 main.go,執行 go run .。
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe("127.0.0.1:8080", mux))
}
開啟 http://127.0.0.1:8080/metrics,即可查看 go_goroutines 與 go_memstats_* 等指標。預設登錄表已註冊 Go 執行階段與程序採集器,實際可用的 process_* 指標則依作業系統而異。若用 prometheus.NewRegistry() 自行建立登錄表,要註冊所需的採集器,再將該登錄表傳給 promhttp.HandlerFor。Prometheus Go 埋點指南(英文)
用三種指標回答不同問題
| 指標 | 記錄的值 | 用來觀察 |
|---|---|---|
http_requests_total |
已從量測處理器返回的呼叫累計數,依路由、HTTP 方法和狀態碼區分 | 同一路由的請求速率與回應結果是否改變 |
http_active_requests |
此程序內目前正在處理的呼叫數 | 同時處理的工作是否增加 |
http_request_duration_seconds |
呼叫在處理器內花費的時間分布,單位是秒 | 估算尾端延遲,或計算落在指定桶邊界內的請求量 |
每秒完成的請求量持平時,處理中的請求仍可能增加。單看這個數字,無法區分是資料庫等得更久,還是有短暫的流量尖峰。把處理時間分布和回應結果一起看,才能縮小範圍。
為已註冊的路由加上量測
停止第一個伺服器,把 main.go 換成下列版本。路由在註冊時就有固定模板,把模板傳給量測包裝器,訂單 ID 留在處理器內。
package main
import (
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
const route = "/orders/{id}"
requests := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Completed calls to the instrumented handler.",
}, []string{"route", "method", "code"})
active := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "http_active_requests",
Help: "Calls currently executing in the instrumented handler.",
})
duration := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Time spent in the instrumented handler in seconds.",
Buckets: []float64{0.01, 0.05, 0.1, 0.3, 0.5, 1, 2.5, 5},
}, []string{"route"})
prometheus.MustRegister(requests, active, duration)
orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "missing" {
http.NotFound(w, r)
return
}
fmt.Fprintln(w, "order", id)
})
labels := prometheus.Labels{"route": route}
instrumented := promhttp.InstrumentHandlerInFlight(active,
promhttp.InstrumentHandlerCounter(requests.MustCurryWith(labels),
promhttp.InstrumentHandlerDuration(duration.MustCurryWith(labels), orders),
),
)
mux := http.NewServeMux()
mux.Handle("GET "+route, instrumented)
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe("127.0.0.1:8080", mux))
}
再次執行 go run .,依序造訪 /orders/123、/orders/missing 和 /metrics。兩筆請求都使用 route="/orders/{id}",code 分別是 200 與 404。換一個訂單 ID,只要其他標籤相同,就會累計到既有的時間序列。路由器直接傳回的未匹配 404、方法不符的 405,以及擷取指標的請求本身,都不經過這層包裝。
處理器返回後才更新 Counter 和 Histogram。若 panic 傳出處理器,這兩項不更新,defer 登記的 Gauge 減量仍會執行。計時涵蓋伺服器的處理器,無法代表客戶端收到回應所花的時間。Go ServeMux 路由(英文) · promhttp 量測中介層(英文)
設定擷取目標,查詢尾端延遲
此設定適用於 Prometheus 與應用程式在同一個網路命名空間的情況。若由另一台主機或容器擷取,請使用採集端可以連線的位址,並限制指標端點的存取。
scrape_configs:
- job_name: go-app
scrape_interval: 15s
static_configs:
- targets: ['127.0.0.1:8080']
成功擷取多次後,第一條查詢會依路由和狀態碼列出每秒請求數。第二條估算各路由的 P99,單位是秒。
sum by (route, code) (rate(http_requests_total{job="go-app"}[5m]))
histogram_quantile(
0.99,
sum by (le, route) (rate(http_request_duration_seconds_bucket{job="go-app"}[5m]))
)
先對每條計數器時間序列求 rate(),再彙總各執行個體。它會補正樣本中可辨識的重置,但抓取間隔內未留下樣本的增量無法還原。彙總傳統直方圖時要保留 le,並讓各執行個體使用相同的桶邊界。如果目標是 300 毫秒,有流量時可用 0.3 秒桶的增長率除以全部觀測的增長率,求得達標比例。Prometheus 查詢函式(英文)
同一端點也可交給觀測雲的 DataKit Prom 採集器(簡體中文)。在 urls 設定可連線的指標網址,移轉查詢或告警前先核對實際儲存的名稱、標籤與單位。若要把請求指標和資源壓力放在一起分析,可接著閱讀 RED 與 USE 指標。
