Prometheus筆記(一)metric type

歡迎加入go語言學習交流羣 636728449git

Prometheus筆記(二)監控go項目實時給grafana展現
Prometheus筆記(一)metric typegithub

Prometheus筆記(一)metric type

Prometheus客戶端庫提供四種核心度量標準類型。 這些目前僅在客戶端庫中區分(以啓用針對特定類型的使用而定製的API)和有線協議。 Prometheus服務器還沒有使用類型信息,並將全部數據展平爲無類型時間序列。(本文全部示例代碼都是使用go來舉例的)golang

一、Counter

計數器是表示單個單調遞增計數器的累積量,其值只能增長或在重啓時重置爲零。 例如,您可使用計數器來表示服務的總請求數,已完成的任務或錯誤總數。 不要使用計數器來監控可能減小的值。 例如,不要使用計數器來處理當前正在運行的進程數,而應該用Gauge。服務器

counter主要有兩個方法:app

//將counter值加1.
Inc()
// 將指定值加到counter值上,若是指定值< 0會panic.
Add(float64)

1.1 Counter

通常 metric 容器使用的步驟都是:ide

​ 一、初始化一個metric容器學習

​ 二、Register註冊容器this

​ 三、向容器中添加值spa

使用舉例:.net

//step1:初始一個counter
pushCounter := prometheus.NewCounter(prometheus.CounterOpts{
    Name: "repository_pushes", // 注意: 沒有help字符串
})
err := prometheus.Register(pushCounter) // 會返回一個錯誤.
if err != nil {
    fmt.Println("Push counter couldn't be registered, no counting will happen:", err)
    return
}

// Try it once more, this time with a help string.
pushCounter = prometheus.NewCounter(prometheus.CounterOpts{
    Name: "repository_pushes",
    Help: "Number of pushes to external repository.",
})

//setp2: 註冊容器
err = prometheus.Register(pushCounter)
if err != nil {
    fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err)
    return
}

pushComplete := make(chan struct{})
// TODO: Start a goroutine that performs repository pushes and reports
// each completion via the channel.
for range pushComplete {
    //step3:向容器中寫入值
    pushCounter.Inc()
}

輸出:

Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string

1.2 CounterVec

CounterVec是一組counter,這些計數器具備相同的描述,但它們的變量標籤具備不一樣的值。 若是要計算按各類維度劃分的相同內容(例如,響應代碼和方法分區的HTTP請求數),則使用此方法。使用NewCounterVec建立實例。

//step1:初始化一個容器
httpReqs := prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_total",
        Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
    },
    []string{"code", "method"},
)
//step2:註冊容器
prometheus.MustRegister(httpReqs)

httpReqs.WithLabelValues("404", "POST").Add(42)

// If you have to access the same set of labels very frequently, it
// might be good to retrieve the metric only once and keep a handle to
// it. But beware of deletion of that metric, see below!
//step3:向容器中寫入值,主要調用容器的方法如Inc()或者Add()方法
m := httpReqs.WithLabelValues("200", "GET")
for i := 0; i < 1000000; i++ {
    m.Inc()
}
// Delete a metric from the vector. If you have previously kept a handle
// to that metric (as above), future updates via that handle will go
// unseen (even if you re-create a metric with the same label set
// later).
httpReqs.DeleteLabelValues("200", "GET")
// Same thing with the more verbose Labels syntax.
httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"})

二、Gauge

2.1 Gauge

Gauge能夠用來存放一個能夠任意變大變小的數值,一般用於測量值,例如溫度或當前內存使用狀況,或者運行的goroutine數量

主要有如下四個方法

// 將Gauge中的值設爲指定值.
Set(float64)
// 將Gauge中的值加1.
Inc()
// 將Gauge中的值減1.
Dec()
// 將指定值加到Gauge中的值上。(指定值能夠爲負數)
Add(float64)
// 將指定值從Gauge中的值減掉。(指定值能夠爲負數)
Sub(float64)

示例代碼(實時統計CPU的溫度):

//step1:初始化容器
cpuTemprature := prometheus.NewGauge(prometheus.GaugeOpts{
    Name:      "CPU_Temperature",
    Help:      "the temperature of CPU",
})
//step2:註冊容器
prometheus.MustRegister(cpuTemprature)
//定時獲取cpu溫度而且寫入到容器
func(){
    tem = getCpuTemprature()
    //step3:向容器中寫入值。調用容器的方法
	cpuTemprature.Set(tem)  
}

2.2 GaugeVec

假設你要一次性統計四個cpu的溫度,這個時候就適合使用GaugeVec了。

cpusTemprature := prometheus.NewGaugeVec(
    prometheus.GaugeOpts{
        Name:      "CPUs_Temperature",
        Help:      "the temperature of CPUs.",
    },
    []string{
        // Which cpu temperature?
        "cpuName",
    },
)
prometheus.MustRegister(cpusTemprature)

cpusTemprature.WithLabelValues("cpu1").Set(temperature1)
cpusTemprature.WithLabelValues("cpu2").Set(temperature2)
cpusTemprature.WithLabelValues("cpu3").Set(temperature3)

三、Summary

Summary從事件或樣本流中捕獲單個觀察,並以相似於傳統彙總統計的方式對其進行彙總:1。觀察總和,2。觀察計數,3。排名估計。典型的用例是觀察請求延遲。 默認狀況下,Summary提供延遲的中位數。

temps := prometheus.NewSummary(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},
})

// Simulate some observations.
for i := 0; i < 1000; i++ {
    temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
}

// Just for demonstration, let's check the state of the summary by
// (ab)using its Write method (which is usually only used by Prometheus
// internally).
metric := &dto.Metric{}
temps.Write(metric)
fmt.Println(proto.MarshalTextString(metric))

四、Histogram

主要用於表示一段時間範圍內對數據進行採樣,(一般是請求持續時間或響應大小),並可以對其指定區間以及總數進行統計,一般咱們用它計算分位數的直方圖。

temps := prometheus.NewHistogram(prometheus.HistogramOpts{
    Name:    "pond_temperature_celsius",
    Help:    "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
    Buckets: prometheus.LinearBuckets(20, 5, 5),  // 5 buckets, each 5 centigrade wide.
})

// Simulate some observations.
for i := 0; i < 1000; i++ {
    temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
}

// Just for demonstration, let's check the state of the histogram by
// (ab)using its Write method (which is usually only used by Prometheus
// internally).
metric := &dto.Metric{}
temps.Write(metric)
fmt.Println(proto.MarshalTextString(metric))

歡迎加入go語言學習交流羣 636728449

2、參考資料

[1] https://godoc.org/github.com/prometheus/client_golang/prometheus
[2] https://prometheus.io/docs/introduction/overview/

相關文章
相關標籤/搜索