引入pprof包

1
import "net/http/pprof"

使用pprof包来进行分析

1
2
3
4
5
6
7
8
内建的分析函数有:
pprof.Index(w http.ResponseWriter, r *http.Request)
pprof.Cmdline(w http.ResponseWriter, r *http.Request)
pprof.Profile(w http.ResponseWriter, r *http.Request)
pprof.Symbol(w http.ResponseWriter, r *http.Request)
pprof.Trace(w http.ResponseWriter, r *http.Request)

以上5个接受的参数,跟net/http的handler一样,所以可以很方便的集成在server的代码里。

最简单的方式

如果server是这样启动的

1
2
3
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()

则只需要简单的引入pprof包即可访问 /debug/pprof 这5个接口

1
import _ "net/http/pprof"

自定义Mux

需手动注册路由规则

1
2
3
4
5
6
import "net/http/pprof"
r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)

第三方web框架 iris

第三方的web框架的handler的入参可能并不是(w http.ResponseWriter, r *http.Request) 这样,因此需要做一次转换。

iris框架里提供的有handlerconv包可以做这样的转换,使用方式如下。

1
2
3
4
5
6
7
8
import "net/http/pprof"
import "github.com/kataras/iris/core/handlerconv"

app.Get("/debug/pprof/", handlerconv.FromStd(pprof.Index))
app.Get("/debug/pprof/cmdline", handlerconv.FromStd(pprof.Cmdline))
app.Get("/debug/pprof/profile", handlerconv.FromStd(pprof.Profile))
app.Get("/debug/pprof/symbol", handlerconv.FromStd(pprof.Symbol))
app.Get("/debug/pprof/trace", handlerconv.FromStd(pprof.Trace))

gc 排查

Golang,自带gc,在不改动代码的情况下,我们可以设置GODEBUG='gctrace=1'环境变量启动程序,来向标准错误输出打印gc log

生成火焰图 gotorch

1 安装flamegraph.pl
1
2
git clone https://github.com/brendangregg/FlameGraph.git
cp flamegraph.pl /usr/local/bin
2 安装go-torch
1
go get -v github.com/uber/go-torch
3 生成火焰图
1
2
cpu:
go-torch -u http://xx.xx.xx.xx:6060 -t 30 -f cpu.svg
1
2
mem:
go-torch -u http://xx.xx.xx.xx:6060/debug/pprof/heap --colors mem -f mem.svg

ref:https://blog.wangriyu.wang/2019/02-fix-memory-leak.html

生成火焰图 pprof

go1.11之后,go tool pprof也可以生成火焰图

1
2
3
4
CPU:
go tool pprof -seconds=10 -http=:8081 http://127.0.0.1:9092/debug/pprof/profile
mem:
go tool pprof -http=:8081 http://127.0.0.1:9092/debug/pprof/heap

debugcharts

可视化gc pause,内存分配和cpu占用等信息,每秒更新

1
2
3
import (	
_ "github.com/mkevac/debugcharts"
)

http://127.0.0.1:6060/debug/charts

查看trace信息

1
2
curl 'http://127.0.0.1:9091/debug/pprof/trace?seconds=10' -o tracelocal.out
go tool trace tracelocal.out