Prometheus 支持 4 種 指標類型,分別是 Counter、Gauge、Histogram 和 Summary。
一般在實際應用場景中,通常一個指標需要對應多條時序數據(Label Name 為維度),此時就需要使用支持標簽的指標類型。
Prometheus 有 4 種支持標簽的指標類型,分別是 ConterVec、GaugeVec、HistogramVec、SummaryVec。
CounterVec 與 Counter 的區別是,它支持 Label,我們可以按照 Lable 維度,將同一個指標的數據按照 Lable 分組統計。例如,同一個 Api 接口的請求數,我們可以定義 Lable (Code、Method),按照狀態碼和 HTTP 請求方式,分組統計同一個 Api 接口的請求數。
示例代碼:
var ( // 標簽名 labelNames = []string{"host", "code", "path", "method"} // HttpReqs 實例化 CounterVec HttpReqs *prometheus.CounterVec = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "http_requests_total", Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", }, labelNames, ))
閱讀上面這段代碼,我們使用 NewCounterVec 創建一個實例,它支持多個方法,我們可以使用其中一個性能相對較高的方法 WithLabelValues,返回一個 Counter。
示例代碼:
func Metrics() gin.HandlerFunc { return func(c *gin.Context) { c.Next() host := c.RemoteIP() code := fmt.Sprintf("%d", c.Writer.Status()) method := c.Request.Method labelsByHttpReqs := []string{host, code, c.FullPath(), method} prometheus_metrics.HttpReqs.WithLabelValues(labelsByHttpReqs...).Inc() }}
Counter 支持兩個方法,分別是 Inc() 和 Add(),其中 Inc() 將 Counter 增加 1,Add() 將 Counter 增加給定值,需要注意的是,給定值必須為非負值,否則會引發 panic。
需要注意的是,在我們創建指標之后,還需要使用 Register() 接口的 Register() 方法,注冊之后才可以被收集到指標數據。如果需要注冊多個指標,可以使用 MustRegister() 方法。
示例代碼:
reg := prometheus.NewRegistry()reg.MustRegister(prometheus_metrics.HttpReqs, prometheus_metrics.OpsQueued, prometheus_metrics.Latencies, prometheus_metrics.Temps)
GaugeVec 與 Gauge 的區別是,它支持 Label,我們可以按照 Lable 維度,將同一個指標的數據按照 Lable 分組統計。
示例代碼:
var ( labelNamesByOpsQueued = []string{ "user", "type", } OpsQueued = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "ops_queued", Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", }, labelNamesByOpsQueued, ))
閱讀上面這段代碼,我們使用 NewGaugeVec 創建實例。
HistogramVec 與 Histogram 的區別是,它支持 Label,我們可以按照 Lable 維度,將同一個指標的數據按照 Lable 分組統計。
示例代碼:
var ( labelNamesByLatencies = []string{"method", "code"} Latencies = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "Tracks the latencies for HTTP requests.", Buckets: []float64{0.99, 0.9, 0.5}, }, labelNamesByLatencies, ))
SummaryVec 與 Summary 的區別是,它支持 Label,我們可以按照 Lable 維度,將同一個指標的數據按照 Lable 分組統計。
示例代碼:
var ( labelNamesByTemps = []string{"species"} Temps = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "pond_temperature_celsius", Help: "The temperature of the frog pond.", Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, }, labelNamesByTemps, ))
閱讀上面這段代碼,使用 NewSummaryVec 創建實例。
本文我們主要介紹 4 種指標類型的含義,通過 Label 可以將 4 種類型的指標數據,按照 Label 的維度分組統計,我們以支持 Label 的 CounterVec 為例,介紹了它的使用方式,其余 3 種支持 Label 的指標也提供了簡單的使用示例。
本文鏈接:http://www.www897cc.com/showinfo-26-56597-0.htmlPrometheus Go client library 詳解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: Python實戰:打造高效多進程TCP服務器,輕松應對并發請求!
下一篇: 11個優秀開源TTS引擎