在網絡應用程序中,監控往往是很重要的,有了監控,才能更好的分析和排查應用程序中的問題,提高效率,實現“事前預警,事后跟蹤”
在當代開源系統中,可以使用grafana和prometheus相互配合,從而進行監控。
1、prometheus是一個監控和報警工具,可以實現對數據的捕捉和采集,所采集的數據會以指標的形式保存在時序數據庫中。
2、grafana是一個開源的可視化工具,可以很好的對接prometheus,十分強大和方便
下面就介紹如何使用這兩種工具進行配合使用,實現對golang的指標進行監控
環境依賴
1、安裝grafana
2、安裝prometheus
3、安裝gin框架
4、mac環境
5、golang環境
安裝grafana
可以訪問grafana的官方網站https://grafana.com/grafana/download,下載對應二進制文件
curl -O [https://dl.grafana.com/enterprise/release/grafana-enterprise-11.1.3.darwin-amd64.tar.gz](https://dl.grafana.com/enterprise/release/grafana-enterprise-11.1.3.darwin-amd64.tar.gz)
tar -zxvf grafana-enterprise-11.1.3.darwin-amd64.tar.gz
啟動grafana,啟動bin目錄下的grafana文件,如下
./bin/grafana server
瀏覽器訪問http://localhost:3000 ,如下啟動成功
安裝prometheus
訪問官方網站https://prometheus.io/download/進行下載對應的二進制
啟動prometheus
./prometheus
瀏覽器訪問http://localhost:9090/,如下啟動成功
代碼實例
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"math/rand"
"net/http"
)
var (
WebRequestTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "web_reqeust_total",
Help: "Number of hello requests in total",
}, []string{"method", "path", "code"})
)
func init() {
prometheus.MustRegister(WebRequestTotal)
}
func main() {
r := gin.Default() //創建gin
r.GET("/", index) //綁定路由
r.GET("/metrics", gin.WrapH(promhttp.Handler()))
// 定義一個健康檢查的路由
r.GET("/health", func(c *gin.Context) {
b := rand.Intn(100)
label := make(prometheus.Labels, 0)
if b <= 50 {
label["code"] = "12"
label["method"] = c.Request.Method
label["path"] = c.Request.URL.Path
WebRequestTotal.With(label).Inc()
} else {
label["code"] = "0"
label["method"] = c.Request.Method
label["path"] = c.Request.URL.Path
WebRequestTotal.With(label).Inc()
}
//WebRequestTotal.WithLabelValues(c.Request.Method, c.Request.URL.Path).Inc()
c.String(http.StatusOK, "OK")
})
r.POST("/update", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
r.Run(":8001") //運行綁定端口
}
func index(c *gin.Context) {
fmt.Println("1111")
c.JSON(200, gin.H{
"message": "go!go!gono!yesyes",
})
}
1、這邊以測試http://localhost:8001/health這個接口為例,統計code不為0的概率是多少
2、需要開放/metrics指標接口,prometheus通過這個接口采集數據到prometheus中時序數據庫中,如下顯示
3、需要把項目的域名寫入到prometheus.yml中的static_configs->targets中,如下,prometheus就會自動采集這個域名中的指標數據
然后重啟prometheus
配置grafana
配置數據源
點擊 設置->data sources
填寫prometheus的域名,如下
配置監控面板
點擊右上角的add panel-> add a new panel
如下,編寫對應的promQl查詢語句
sum(increase(web_reqeust_total{path="/health", code!="0"}[5m])) /
sum(increase(web_reqeust_total{path="/health"}[5m])) > 0 or on() vector(0)
并且開啟Visibility和設置對應的Values為Mean、Min和Max
這樣就能統計出每個時間段對應的請求的http錯誤率了,這邊的錯誤率是通過code來判斷,code非0的請求數/總共的請求數