https://go.dev/blog/pprof https://pkg.go.dev/net/http/pprof

配置监听端口

  1. package main
  2. import (
  3. "flag"
  4. "log"
  5. "net/http"
  6. _ "net/http/pprof"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. )
  11. func init() {
  12. // ...
  13. }
  14. func main() {
  15. // ...
  16. go func() {
  17. log.Println(http.ListenAndServe("localhost:10001", nil))
  18. }()
  19. // ...
  20. }

使用方式

1、pprof工具查看heap profile:

  1. go tool pprof http://localhost:6060/debug/pprof/heap

2、查看 30 秒的 CPU 配置文件:

  1. go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

3、程序中调用 runtime.SetBlockProfileRate 后查看 goroutine 阻塞配置文件:

  1. go tool pprof http://localhost:6060/debug/pprof/block

4、您的程序中调用 runtime.SetMutexProfileFraction 后查看竞争互斥锁的持有者:

  1. go tool pprof http://localhost:6060/debug/pprof/mutex

5、收集15秒执行跟踪:

  1. wget -O trace.out http://localhost:6060/debug/pprof/trace?seconds=15
  2. go tool trace trace.out

通过工具查看生产的配置文件

  1. 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

  1. {"/debug/pprof/<script>scripty<script>", Index, http.StatusNotFound, "text/plain; charset=utf-8", "", []byte("Unknown profile\n")},
  2. {"/debug/pprof/heap", Index, http.StatusOK, "application/octet-stream", `attachment; filename="heap"`, nil},
  3. {"/debug/pprof/heap?debug=1", Index, http.StatusOK, "text/plain; charset=utf-8", "", nil},
  4. {"/debug/pprof/cmdline", Cmdline, http.StatusOK, "text/plain; charset=utf-8", "", nil},
  5. {"/debug/pprof/profile?seconds=1", Profile, http.StatusOK, "application/octet-stream", `attachment; filename="profile"`, nil},
  6. {"/debug/pprof/symbol", Symbol, http.StatusOK, "text/plain; charset=utf-8", "", nil},
  7. {"/debug/pprof/trace", Trace, http.StatusOK, "application/octet-stream", `attachment; filename="trace"`, nil},
  8. {"/debug/pprof/mutex", Index, http.StatusOK, "application/octet-stream", `attachment; filename="mutex"`, nil},
  9. {"/debug/pprof/block?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="block-delta"`, nil},
  10. {"/debug/pprof/goroutine?seconds=1", Index, http.StatusOK, "application/octet-stream", `attachment; filename="goroutine-delta"`, nil},
  11. {"/debug/pprof/", Index, http.StatusOK, "text/html; charset=utf-8", "", []byte("Types of profiles available:")},