golang profile怎么用
引入pprof包
1 | import "net/http/pprof" |
使用pprof包来进行分析
1 | 内建的分析函数有: |
最简单的方式
如果server是这样启动的1
2
3go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
则只需要简单的引入pprof包即可访问 /debug/pprof 这5个接口1
import _ "net/http/pprof"
自定义Mux
需手动注册路由规则1
2
3
4
5
6import "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 | import "net/http/pprof" |
gc 排查
Golang,自带gc,在不改动代码的情况下,我们可以设置GODEBUG='gctrace=1'
环境变量启动程序,来向标准错误输出打印gc log
生成火焰图 gotorch
1 安装flamegraph.pl
1 | git clone https://github.com/brendangregg/FlameGraph.git |
2 安装go-torch
1 | go get -v github.com/uber/go-torch |
3 生成火焰图
1 | cpu: |
1 | mem: |
ref:https://blog.wangriyu.wang/2019/02-fix-memory-leak.html
生成火焰图 pprof
go1.11之后,go tool pprof也可以生成火焰图
1 | CPU: |
debugcharts
可视化gc pause,内存分配和cpu占用等信息,每秒更新
1 | import ( |
http://127.0.0.1:6060/debug/charts
查看trace信息
1 | curl 'http://127.0.0.1:9091/debug/pprof/trace?seconds=10' -o tracelocal.out |