1. 程式人生 > 程式設計 >詳解prometheus監控golang服務實踐記錄

詳解prometheus監控golang服務實踐記錄

一、prometheus基本原理介紹

prometheus是基於metric取樣的監控,可以自定義監控指標,如:服務每秒請求數、請求失敗數、請求執行時間等,每經過一個時間間隔,資料都會從執行的服務中流出,儲存到一個時間序列資料庫中,之後可通過PromQL語法查詢。

主要特點:

多維資料模型,時間序列資料通過metric名以key、value的形式標識;

使用PromQL語法靈活地查詢資料;

不需要依賴分散式儲存,各伺服器節點是獨立自治的;

時間序列的收集,通過 HTTP 呼叫,基於pull 模型進行拉取;

通過push gateway推送時間序列;

通過服務發現或者靜態配置,來發現目標服務物件;

多種繪圖和儀表盤的視覺化支援;

二、prometheus使用docker部署

檢視是否有映象

sudo docker search prometheus

新建prometheus.yaml

global:
scrape_interval: 10s
evaluation_interval: 60s


scrape_configs:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: integral
static_configs:
- targets: ['10.20.xx.xx:8001']

執行:

docker run --name prometheus -p 9090:9090 -v ~/prometheus.yaml:/etc/prometheus/prometheus.yml prom/prometheus

進入容器中可以看到配置檔案已對映到容器指定目錄:

詳解prometheus監控golang服務實踐記錄

踩坑: prometheus官方映象指定的配置檔案是prometheus.yml 所以對映到容器內的檔名一定要保持一致 否則會出現指定的配置檔案不生效

三、prometheus整體架構及各元件

詳解prometheus監控golang服務實踐記錄

Prometheus Server :主程式,負責抓取和儲存時序資料;

Client Libraries:客戶端庫,負責檢測應用程式程式碼;

Push Gateway:Push 閘道器,接收短生命週期的 Job 主動推送的時序資料;

Exporters:為不同服務定製的Exporter(如:HAProxy、StatsD、Graphite等) ,從而抓取它們的Metris指標資料;

Alert Manage:告警管理器,處理不同的告警;

四、prometheus客戶端呼叫示例

自定義prometheus的gin中介軟體

package ginprometheus
 
import (
  "strconv"
  "sync"
  "time"
 
  "github.com/gin-gonic/gin"
  "github.com/prometheus/client_golang/prometheus"
)
 
const (
  metricsPath = "/metrics"
  faviconPath = "/favicon.ico"
)
 
var (
  // httpHistogram prometheus 模型
  httpHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{
    Namespace:  "http_server",Subsystem:  "",Name:    "requests_seconds",Help:    "Histogram of response latency (seconds) of http handlers.",ConstLabels: nil,Buckets:   nil,},[]string{"method","code","uri"})
)
 
// init 初始化prometheus模型
func init() {
  prometheus.MustRegister(httpHistogram)
}
 
// handlerPath 定義取樣路由struct
type handlerPath struct {
  sync.Map
}
 
// get 獲取path
func (hp *handlerPath) get(handler string) string {
  v,ok := hp.Load(handler)
  if !ok {
    return ""
  }
  return v.(string)
}
 
// set 儲存path到sync.Map
func (hp *handlerPath) set(ri gin.RouteInfo) {
  hp.Store(ri.Handler,ri.Path)
}
 
// GinPrometheus gin呼叫Prometheus的struct
type GinPrometheus struct {
  engine *gin.Engine
  ignored map[string]bool
  pathMap *handlerPath
  updated bool
}
 
type Option func(*GinPrometheus)
 
// Ignore 新增忽略的路徑
func Ignore(path ...string) Option {
  return func(gp *GinPrometheus) {
    for _,p := range path {
      gp.ignored[p] = true
    }
  }
}
 
// New new gin prometheus
func New(e *gin.Engine,options ...Option) *GinPrometheus {
  if e == nil {
    return nil
  }
 
  gp := &GinPrometheus{
    engine: e,ignored: map[string]bool{
      metricsPath: true,faviconPath: true,pathMap: &handlerPath{},}
 
  for _,o := range options {
    o(gp)
  }
  return gp
}
 
// updatePath 更新path
func (gp *GinPrometheus) updatePath() {
  gp.updated = true
  for _,ri := range gp.engine.Routes() {
    gp.pathMap.set(ri)
  }
}
 
// Middleware set gin middleware
func (gp *GinPrometheus) Middleware() gin.HandlerFunc {
  return func(c *gin.Context) {
    if !gp.updated {
      gp.updatePath()
    }
    // 過濾請求
    if gp.ignored[c.Request.URL.String()] {
      c.Next()
      return
    }
 
    start := time.Now()
    c.Next()
 
    httpHistogram.WithLabelValues(
      c.Request.Method,strconv.Itoa(c.Writer.Status()),gp.pathMap.get(c.HandlerName()),).Observe(time.Since(start).Seconds())
  }
}

gin路由初始化prometheus,使用中介軟體取樣

gp := ginprometheus.New(r)
r.Use(gp.Middleware())
// metrics取樣
r.GET("/metrics",gin.WrapH(promhttp.Handler()))

詳解prometheus監控golang服務實踐記錄

檢視target

詳解prometheus監控golang服務實踐記錄

選取指標對應的graph,這裡以gc取樣的時間為例:

詳解prometheus監控golang服務實踐記錄

如果需要展示更為豐富的視覺化看板,可以將prometheus與grafana結合,將prometheus資料接入到grafana中,此處不再過多闡述

到此這篇關於詳解prometheus監控golang服務實踐記錄的文章就介紹到這了,更多相關prometheus監控golang服務內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!