prometheus自定義metrics

項(xiàng)目地址 個(gè)人博客

日常項(xiàng)目開發(fā)過程中為了觀察項(xiàng)目的線上運(yùn)行指標(biāo)通常需要項(xiàng)目提供一系列指標(biāo)信息,我們目前用的prometheus,而項(xiàng)目當(dāng)然要提供一系列prometheus metrics指標(biāo)信息,但是默認(rèn)官方golang的倉庫不是很好用。

  • 所有指標(biāo)全部保存在內(nèi)存重啟后會(huì)全部清零
  • 如果指標(biāo)labels數(shù)量變更,無法重新注冊(cè),unregister貌似無效
  • 無法定時(shí)清除數(shù)據(jù),比如我想觀察某些指標(biāo)每一天的數(shù)據(jù)
  • web服務(wù)很多通用的http接口指標(biāo)需要重復(fù)定義并自己定義中間件收集

于是乎找到github上一個(gè)很好的項(xiàng)目,可以滿足上面所有需求可以大多數(shù)一般項(xiàng)目開發(fā)過程中的metrics需求,使用起來也比較簡(jiǎn)單。下面來自項(xiàng)目READEME:

lib-metrics

image.png

GoDoc

Dependency

github.com/AlecAivazis/survey/v2 v2.0.1 // indirect
github.com/atotto/clipboard v0.1.2 // indirect
github.com/go-redis/redis v6.15.2+incompatible
github.com/golang/protobuf v1.3.1
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/prometheus/client_golang v1.0.0
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
github.com/prometheus/common v0.6.0
gopkg.in/robfig/cron.v2 v2.0.0-20150107220207-be2e0b0deed5
gopkg.in/yaml.v2 v2.2.2 // indirect

Initialization

init global collector gather

subsystem := "test"
metricsCollector = NewAutumnCollector(subsystem)

create local metric and registry

localMetrics = metricsCollector.NewAutumnLocalMetric("local_test", "local_type")
// Reset data at zero every day
localMetrics.ResetByCron("0 0 * * *")
metricsCollector.Register(localMetrics)

create metric base on redis and registry

redisMetric = metricsCollector.NewAutumnRedisMetric(client, "redis_test", "type")
// reset redis key
redisMetric.ResetMetricRedisKey("reset_redis_key_test")
// get now redis key
redisMetric.GetRedisKey()
// Reset data at zero every day
redisMetric.ResetByCron("0 0 * * *")
// registry metric
metricsCollector.Register(redisMetric)

Register HTTP handler middleware to customize metrics for collecting HTTP requests

// Collect interface responses
var standardRequestDuration = prometheus.NewHistogramVec(
    prometheus.HistogramOpts{
        Name:    "server_request_duration_seconds",
        Help:    "How much time costs(s)",
        Buckets: []float64{0.0005, 0.001, 0.002, 0.005, 0.010, 0.020, 0.050, 0.1, 0.5, 1, 5},
    }, []string{"code", "router"})

metricsCollector.RegisterPrometheus(standardRequestDuration)

// Pre-interceptor record start time
metricsCollector.UseBeforeHandlerHook(func(ctx *Context) {
    fmt.Println("this is before 1 start")
    start := time.Now()
    ctx.Set("start", start)
    fmt.Println("this is before 1 end")
})

// the post-interceptor calculates the response time and obtains information such as code, which is set by Observer.
metricsCollector.UseAfterHandlerHook(func(ctx *Context) {
    fmt.Println("this is after 1 start")
    start := ctx.GetTime("start")
    elapsed := time.Since(start).Seconds()
    standardRequestDuration.WithLabelValues(fmt.Sprint(ctx.ResponseWriter.Status()), ctx.Request.URL.Path).Observe(elapsed)
    fmt.Println("this is after 1 end")
})

Usage

// local metrics
localMetrics.Set(1,"1")
localMetrics.Incr("2")
localMetrics.Add(1,"3")

// redis metrics
redisMetric.Set(1,"1")
redisMetric.Incr("2")
redisMetric.Add(1,"3")

// Using native metric
standardRequestDuration.WithLabelValues(200, "/test").Observe(10)

Registry Handler

Register gin middleware and add metrics interface to collect HTTP metrics information

engine = gin.New()
// add gin middleware
engine.Use(func(ctx *gin.Context) {
    metricsCollector.Use(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
        ctx.Next()
    })).ServeHTTP(ctx.Writer,ctx.Request)
})
// Register gin interface to provide metrics interface
engine.Get(DefaultMetricPath, gin.WrapF(metricsCollector.Handler()))

Register native HTTP Middleware

engine = new(http.ServeMux)
h:=metricsCollector.Use(engine)
engine.Handle(DefaultMetricPath, metricsCollector.Handler())
http.ListenAndServe(":8080", h)

Built-in default HTTP service startup metrics interface

if err := metricsCollector.ListenAndServe(":8080",metricsCollector.Handler); err != nil && err != http.ErrServerClosed {
     panic(err)
}

項(xiàng)目地址 個(gè)人博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容