Go服务监控

使用Golang能够开发出高性能的HTTP、GRPC服务。通常项目运行后,咱们也须要监控服务的性能或者进行调试。除了打日志,还有没有其余可视化的方案呢?答案是有的。git

本文将会介绍几种经常使用的监控方案。github

pprof

这个是go语言自带的。启用很简单:golang

_ "net/http/pprof"

仅需显式的在 main 包的 import 里增长上面一行便可。完整使用示例:web

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/就能看到监控的一些信息了:浏览器

注:生产环境通常不会按上面那么写,通常都是开个协程:bash

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

如何启动 PProf 可视化界面?app

须要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、协程等变化状况的可视化工具。

跟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 。

一、入口文件增长代码:

//监控
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)
}()

二、import增长

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

参考

一、Golang pprof详解
https://studygolang.com/articles/14519
二、mkevac/debugcharts: Very simple charts with some debug data for Go programs
https://github.com/mkevac/debugcharts
三、prometheus/client_golang: Prometheus instrumentation library for Go applications
https://github.com/prometheus/client_golang/

相关文章
相关标签/搜索