prometheus是一個(gè)開源的系統(tǒng)監(jiān)控和報(bào)警工具曹动,作為新一代的云原生監(jiān)控系統(tǒng),它可以和grafana等開源組件很好的結(jié)合在一起饰恕,也為golang提供了對(duì)應(yīng)的集成工具
這邊我主要介紹gin框架中如何集成prometheus來實(shí)現(xiàn)統(tǒng)計(jì)http方法和路徑
一挠羔、包依賴
在系統(tǒng)中先安裝好對(duì)應(yīng)的prometheus包,如下
go get github.com/gin-gonic/gin
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
二埋嵌、代碼實(shí)例
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"time"
)
var (
WebRequestTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "web_reqeust_total",
Help: "Number of hello requests in total",
}, []string{"method", "path"})
WebRequestDurationHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Histogram of the duration of HTTP requests",
Buckets: prometheus.DefBuckets,
}, []string{"method", "path"})
)
func init() {
// 注冊(cè)計(jì)數(shù)器到 Prometheus
prometheus.MustRegister(WebRequestTotal)
// 注冊(cè)直方圖到 Prometheus
prometheus.MustRegister(WebRequestDurationHistogram)
}
func main() {
r := gin.Default() //創(chuàng)建gin
r.Use(func(c *gin.Context) {
start := time.Now()
//處理請(qǐng)求
c.Next()
duration := time.Since(start).Seconds()
//記錄請(qǐng)求次數(shù)
WebRequestTotal.WithLabelValues(c.Request.Method, c.Request.URL.Path).Inc()
//記錄http方法和路徑對(duì)應(yīng)的耗時(shí)
WebRequestDurationHistogram.WithLabelValues(c.Request.Method, c.Request.URL.Path).Observe(duration)
})
r.GET("/", index) //綁定路由
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
// 定義一個(gè)健康檢查的路由
r.GET("/health", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
r.POST("/update", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
r.Run(":8001") //運(yùn)行綁定端口
}
func index(c *gin.Context) {
fmt.Println("1111")
c.JSON(200, gin.H{
"message": "go!go!gono!yesyes",
})
}
說明
1破加、WebRequestTotal這是一個(gè)“CounterVec”類型的計(jì)數(shù)器,用于統(tǒng)計(jì)不同http方法和路徑的請(qǐng)求次數(shù)
2雹嗦、WebRequestDurationHistogram這是一個(gè)“HistogramVe”類型的直方圖拌喉,用于記錄不同http方法和路徑的請(qǐng)求持續(xù)時(shí)間,使用了“prometheus.DefBucket”提供的默認(rèn)的桶分布俐银,當(dāng)然這個(gè)也可以自定義
3尿背、采用了中間件
a、使用中間件攔截了請(qǐng)求捶惜,當(dāng)結(jié)束后更新對(duì)應(yīng)的計(jì)數(shù)器
b田藐、在中間件在請(qǐng)求開始和請(qǐng)求結(jié)束分別記錄了時(shí)間,得到請(qǐng)求的耗時(shí)吱七,并且記錄到了直方圖中
4汽久、通過訪問http://localhost:8001/metrics來實(shí)現(xiàn)對(duì)指標(biāo)的查詢
如下顯示的是不同http方法和路徑的請(qǐng)求次數(shù)
如下則顯示的是不同http方法和路徑的請(qǐng)求持續(xù)時(shí)間,安裝桶進(jìn)行分布