1
0

goroutines.go 940 B

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