我可能在滥用 promhttp.Handler()
来实现我的微服务的用例,告诉我:
- 版本
- 如果它有数据库连接
如果有更好的方法来监控我的微服务,请告诉我!
我不确定如何以这样一种方式构造句柄,即在调用/metrics 时,db.Ping()重新评估。
https://s.natalian.org/2019-06-02/msping.mp4
package main
import (
"log"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const version = "0.0.1"
type App struct {
Router *mux.Router
DB *sqlx.DB
}
func main() {
a := App{}
a.Initialize()
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), a.Router))
}
func (a *App) Initialize() {
connectionString := "root:secret@tcp(localhost:3306)/rest_api_example?multiStatements=true&sql_mode=TRADITIONAL&timeout=5s"
var err error
a.DB, err = sqlx.Open("mysql", connectionString)
if err != nil {
log.Fatal(err)
}
microservicecheck := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "mscheck",
Help: "Version with DB ping check",
},
[]string{
"commit",
},
)
if a.DB.Ping() == nil {
microservicecheck.WithLabelValues(version).Set(1)
} else {
microservicecheck.WithLabelValues(version).Set(0)
}
prometheus.MustRegister(microservicecheck)
a.Router = mux.NewRouter()
a.initializeRoutes()
}
func (a *App) initializeRoutes() {
a.Router.Handle("/metrics", promhttp.Handler()).Methods("GET")
}
最佳答案
您还可以添加一个执行 preflight routine 的中间件 Hook (即您的 ping 测试)在调用 promhttp.Handler()
之前。但是,在收集时,我认为应该已经统计了指标;而不是在收集实例中生成。所以……
尝试一个单独的 go-routine,它将定期轮询数据库连接的健康状况。这避免了任何困惑的 Hook 或自定义收集器:
var pingPollingFreq = 5 * time.Second // this should probably match the Prometheus scrape interval
func (a *App) Initialize() {
// ...
prometheus.MustRegister(microservicecheck)
go func() {
for {
if a.DB.Ping() == nil {
microservicecheck.WithLabelValues(version).Set(1)
} else {
microservicecheck.WithLabelValues(version).Set(0)
}
time.Sleep(pingPollingFreq)
}
}()
// ...
}
关于go - 如何在数据库更改时重新评估 promhttp.Handler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56412460/