微服務基本功:增加便利的監控服務指標

log、metrics、trace 是我們觀測和監控微服務的三大法寶,而對於 metrics,我們嚐嚐採集服務的指標,把它們推送到 Prometheus、InfluxDB 等時序數據庫中,並使用 Grafana 展示出來。

如果你有相應的這些基礎架構平臺,那沒有問題。但是如果你缺乏這些基礎的監控平臺,而且有時候也只是臨時想監控一下服務的指標,那麼 rpcx 給你提供了一個極簡的方法,你只需在 rpcx 的服務器添加下面一行:

s.EnableProfile = true

也就是開啓Profile模式,就可以可以在瀏覽器中查看服務基本的指標:

不需要配置監控的服務器地址和端口,不需要配置 profile 和 metric 採集,一切都是自動實現的。

那麼 rpcx 是怎麼實現的呢?

首先,得益於 rpcx 最早在微服務框架中採用的共享端口的方法,我們在服務監聽的端口上增加了一個 http 的服務,支持監控指標的展示,同時也提供了對 go profile 的 API:

mux := http.NewServeMux()
 mux.HandleFunc("/debug/pprof/", pprof.Index)
 mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
 mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
 mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
 mux.HandleFunc("/debug/pprof/trace", pprof.Trace)

 for _, v := range mgr.Views {
  page.AddCharts(v.View())
  mux.HandleFunc("/debug/statsview/view/"+v.Name(), v.Serve)
 }

 mux.HandleFunc("/debug/statsview", func(w http.ResponseWriter, _ *http.Request) {
  page.Render(w)
 })

 staticsPrev := "/debug/statsview/statics/"
 mux.HandleFunc(staticsPrev+"echarts.min.js", func(w http.ResponseWriter, _ *http.Request) {
  w.Write([]byte(statics.EchartJS))
 })

 mux.HandleFunc(staticsPrev+"jquery.min.js", func(w http.ResponseWriter, _ *http.Request) {
  w.Write([]byte(statics.JqueryJS))
 })

 mux.HandleFunc(staticsPrev+"themes/westeros.js", func(w http.ResponseWriter, _ *http.Request) {
  w.Write([]byte(statics.WesterosJS))
 })

 mux.HandleFunc(staticsPrev+"themes/macarons.js", func(w http.ResponseWriter, _ *http.Request) {
  w.Write([]byte(statics.MacaronsJS))
 })

 mgr.srv.Handler = cors.AllowAll().Handler(mux)

其次,集成 go-echarts/statsview[1] 這個實時的 go 運行時 profiler, 它是基於 go-echarts[2], 可以方便的在 Go 語言中使用 echarts 繪圖框架。 不過這個庫兩年沒有更新維護了,我發現其中的一個 bug, 也就是 Y 軸不能顯示標籤,還有不方便創建自定義的監控視圖,所以我 fork 了一份,方便使用 smallnest/statsview[3]。能夠在 rpcx 中快速實現 metrics 監控的功能主要得益於這個框架。

最後,我們在監控圖中增加了最常用的三個指標:

而且,基於 statsview 庫,將來我們可以增加更多的監控 viewer。

參考資料

[1]

go-echarts/statsview: https://github.com/go-echarts/statsview

[2]

go-echarts: https://github.com/go-echarts/go-echarts

[3]

smallnest/statsview: https://github.com/smallnest/statsview

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/GrqKxrn0U3p1OZKKWOEwhw