配置监听端口
package main
import (
"flag"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
)
func init() {
// ...
}
func main() {
// ...
go func() {
log.Println(http.ListenAndServe("localhost:10001", nil))
}()
// ...
}
使用方式
1、pprof工具查看heap profile:
go tool pprof http://localhost:6060/debug/pprof/heap
2、查看 30 秒的 CPU 配置文件:
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
3、程序中调用 runtime.SetBlockProfileRate 后查看 goroutine 阻塞配置文件:
go tool pprof http://localhost:6060/debug/pprof/block
4、您的程序中调用 runtime.SetMutexProfileFraction 后查看竞争互斥锁的持有者:
go tool pprof http://localhost:6060/debug/pprof/mutex
5、收集15秒执行跟踪:
wget -O trace.out http://localhost:6060/debug/pprof/trace?seconds=15
go tool trace trace.out
通过工具查看生产的配置文件
go tool pprof -http=:10081 profile.xxx.gz
例子
path:/opt/homebrew/Cellar/go@1.16/1.16.10/libexec/src/net/http/pprof/pprof_test.go
{"/debug/pprof/<script>scripty<script>", Index, http.StatusNotFound, "text/plain; charset=utf-8", "", []byte("Unknown profile\n")},
{"/debug/pprof/heap", Index, http.StatusOK, "application/octet-stream", `attachment; filename="heap"`, nil},
{"/debug/pprof/heap?debug=1", Index, http.StatusOK, "text/plain; charset=utf-8", "", nil},
{"/debug/pprof/cmdline", Cmdline, http.StatusOK, "text/plain; charset=utf-8", "", nil},
{"/debug/pprof/profile?seconds=1", Profile, http.StatusOK, "application/octet-stream", `attachment; filename="profile"`, nil},
{"/debug/pprof/symbol", Symbol, http.StatusOK, "text/plain; charset=utf-8", "", nil},
{"/debug/pprof/trace", Trace, http.StatusOK, "application/octet-stream", `attachment; filename="trace"`, nil},
{"/debug/pprof/mutex", Index, http.StatusOK, "application/octet-stream", `attachment; filename="mutex"`, nil},
{"/debug/pprof/block?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="block-delta"`, nil},
{"/debug/pprof/goroutine?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="goroutine-delta"`, nil},
{"/debug/pprof/", Index, http.StatusOK, "text/html; charset=utf-8", "", []byte("Types of profiles available:")},