如何使用 gin 作为服务器来编写 prometheus 导出器指标
Posted
技术标签:
【中文标题】如何使用 gin 作为服务器来编写 prometheus 导出器指标【英文标题】:How to use gin as a server to write prometheus exporter metrics 【发布时间】:2021-04-12 22:58:39 【问题描述】:这是官方prometheus golang-client示例:
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts
Name: "cpu_temperature_celsius",
Help: "Current temperature of the CPU.",
)
func init()
// Metrics have to be registered to be exposed:
prometheus.MustRegister(cpuTemp)
func main()
cpuTemp.Set(65.3)
// The Handler function provides a default handler to expose metrics
// via an HTTP server. "/metrics" is the usual endpoint for that.
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
在此代码中,http 服务器使用promhttp
库。
在使用gin
框架时如何修改指标处理程序?我在documentation 中没有找到答案。
【问题讨论】:
gqlgen.com/recipes/gin 【参考方案1】:我们只使用promhttp
处理程序。
package main
import (
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts
Name: "cpu_temperature_celsius",
Help: "Current temperature of the CPU.",
)
func init()
prometheus.MustRegister(cpuTemp)
func prometheusHandler() gin.HandlerFunc
h := promhttp.Handler()
return func(c *gin.Context)
h.ServeHTTP(c.Writer, c.Request)
func main()
cpuTemp.Set(65.3)
r := gin.New()
r.GET("/", func(c *gin.Context)
c.JSON(200, "Hello world!")
)
r.GET("/metrics", prometheusHandler())
r.Run()
或者我们总是可以切换到 Prometheus 中间件 - https://github.com/zsais/go-gin-prometheus
【讨论】:
【参考方案2】:我正在使用 prometheus 和其他库 https://github.com/Depado/ginprom:
package main
import (
"github.com/Depado/ginprom"
"github.com/gin-gonic/gin"
)
func main()
r := gin.Default()
p := ginprom.New(
ginprom.Engine(r),
ginprom.Subsystem("gin"),
ginprom.Path("/metrics"),
)
r.Use(p.Instrument())
r.GET("/hello/:id", func(c *gin.Context) )
r.GET("/world/:id", func(c *gin.Context) )
r.Run("127.0.0.1:8080")
【讨论】:
以上是关于如何使用 gin 作为服务器来编写 prometheus 导出器指标的主要内容,如果未能解决你的问题,请参考以下文章