Go服務監控


使用Golang可以開發出高性能的HTTP、GRPC服務。一般項目運行后,我們也需要監控服務的性能或者進行調試。除了打日志,還有沒有其他可視化的方案呢?答案是有的。

本文將會介紹幾種常用的監控方案。

pprof

這個是go語言自帶的。啟用很簡單:

_ "net/http/pprof"

僅需顯式的在 main 包的 import 里增加上面一行即可。完整使用示例:

package main

import (
	"net/http"
	_ "net/http/pprof"
)

func main(){
    //提供給負載均衡探活以及pprof調試
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	http.ListenAndServe(":10108", nil)
}

運行之后,在瀏覽器打開 http://127.0.0.1:10108/debug/pprof/就能看到監控的一些信息了:

注:生產環境一般不會按上面那么寫,都是開個協程:

go http.ListenAndServe(":10108", nil)

如何啟動 PProf 可視化界面?

需要graphviz支持,可以到 http://www.graphviz.org/download/ 下載,並把bin加入到環境變量。Mac可以使用brew安裝。

下面以heap為例:

方法一:

go tool pprof -http=:8081 http://localhost:10108/debug/pprof/heap

方法二:

go tool pprof http://localhost:10108/debug/pprof/heap

然后在交互式命令行輸入web即可跳轉到默認瀏覽器:

查看協程信息:

go tool pprof -http=:8081 http://localhost:10108/debug/pprof/goroutine

debugcharts

一個可以實時查看golang程序內存、CPU、GC、協程等變化情況的可視化工具。

debugcharts 監控占用內存大,生產環境不建議開啟。

跟pprof一樣, import引入, 然后開端口監聽就行了:

_ "github.com/mkevac/debugcharts"
//省略其它代碼...
http.ListenAndServe(":10108", nil)

運行后,瀏覽器打開 http://localhost:10108/debug/charts/ 就能看到了:

prometheus

prometheus是grafana的插件,支持go監控的可視化。

首先需要代碼里引入包:

"github.com/prometheus/client_golang/prometheus/promhttp"

然后增加路由:

//prometheus
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":10108", nil)

配置grafana后,效果圖:

一個端口開啟 pprof+charts+prometheus

如果每一個監控都開一個端口就有點浪費端口了。可以在一個端口里開啟 pprof+charts+prometheus 。

1、入口文件增加代碼:

//監控
go func() {
   //提供給負載均衡探活
   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
      w.Write([]byte("ok"))

   })

   //prometheus
   http.Handle("/metrics", promhttp.Handler())

   //pprof, go tool pprof -http=:8081 http://$host:$port/debug/pprof/heap
   http.ListenAndServe(":10108", nil)
}()

2、import增加

_ "github.com/mkevac/debugcharts"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
_ "net/http/pprof"

參考

1、Golang pprof詳解
https://studygolang.com/articles/14519
2、mkevac/debugcharts: Very simple charts with some debug data for Go programs
https://github.com/mkevac/debugcharts
3、prometheus/client_golang: Prometheus instrumentation library for Go applications
https://github.com/prometheus/client_golang/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM