goroutines.go 740 B

123456789101112131415161718192021222324252627282930313233343536
  1. //go:build linux || darwin
  2. // +build linux darwin
  3. package proc
  4. import (
  5. "fmt"
  6. "os"
  7. "path"
  8. "runtime/pprof"
  9. "syscall"
  10. "time"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. )
  13. const (
  14. goroutineProfile = "goroutine"
  15. debugLevel = 2
  16. )
  17. func dumpGoroutines() {
  18. command := path.Base(os.Args[0])
  19. pid := syscall.Getpid()
  20. dumpFile := path.Join(os.TempDir(), fmt.Sprintf("%s-%d-goroutines-%s.dump",
  21. command, pid, time.Now().Format(timeFormat)))
  22. logx.Infof("Got dump goroutine signal, printing goroutine profile to %s", dumpFile)
  23. if f, err := os.Create(dumpFile); err != nil {
  24. logx.Errorf("Failed to dump goroutine profile, error: %v", err)
  25. } else {
  26. defer f.Close()
  27. pprof.Lookup(goroutineProfile).WriteTo(f, debugLevel)
  28. }
  29. }