golang[84]-http/pprof

pprof的使用

1
import _ "net/http/pprof"

如果没有htpp服务器,则需要开一个goroutine 开启http

go func() {
log.Println(http.ListenAndServe(“localhost:6060”, nil))
}()

如果你本身就是一个http服务器,要注意直接添加可能没效果,因为其使用了默认的mux。

httprouter的使用办法:

1
2
3
Route{"pprof", "GET", "/debug/*name", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
http.DefaultServeMux.ServeHTTP(writer,request)
} },

If you’re using a github.com/gorilla/mux.Router you can simply hand off any request prefixed with /debug/ to the http.DefaultServeMux.

1
2
3
import _ "net/http/debug"
router := mux.NewRouter()
router.PathPrefix("/debug/").Handler(http.DefaultServeMux)

or

1
2
3
4
5
6
7
func init() {
http.Handle("/debug/pprof/", http.HandlerFunc(Index))
http.Handle("/debug/pprof/cmdline", http.HandlerFunc(Cmdline))
http.Handle("/debug/pprof/profile", http.HandlerFunc(Profile))
http.Handle("/debug/pprof/symbol", http.HandlerFunc(Symbol))
http.Handle("/debug/pprof/trace", http.HandlerFunc(Trace))
}

使用方式

go tool pprof http://localhost:6060/debug/pprof/goroutine
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/threadcreate
go tool pprof http://localhost:6060/debug/pprof/block
go tool pprof http://localhost:6060/debug/pprof/mutex

会进入命令面板
常用的有top

查看cup:
go tool pprof ./hyperkube http://192.168.1.7:9970/debug/pprof/profile

trace

注意下面的代码对于cgo不支持
curl http://127.0.0.1:6060/debug/pprof/trace?seconds=20 > trace.out
go tool trace trace.out

如果吧下面的代码写入main函数中,会生成trace文件,但是注意,必须要程序停止后才能执行trace.out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
"os"
"runtime/trace"
)

func main() {
//trace
f, err := os.Create("trace.out")
if err != nil {
panic(err)
}
err = trace.Start(f)
if err != nil {
panic(err)
}
defer func() {
trace.Stop()
panic(f.Close())
}()

// Your program here
}