go-zero/core/proc/goroutines.go

46 lines
943 B
Go
Raw Permalink Normal View History

2025-01-28 11:11:49 +08:00
//go:build linux || darwin || freebsd
2020-07-26 17:09:05 +08:00
package proc
import (
"fmt"
"os"
"path"
"runtime/pprof"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
2020-07-26 17:09:05 +08:00
)
const (
goroutineProfile = "goroutine"
debugLevel = 2
)
2023-06-12 01:22:20 +08:00
type creator interface {
Create(name string) (file *os.File, err error)
}
func dumpGoroutines(ctor creator) {
2020-07-26 17:09:05 +08:00
command := path.Base(os.Args[0])
pid := syscall.Getpid()
dumpFile := path.Join(os.TempDir(), fmt.Sprintf("%s-%d-goroutines-%s.dump",
command, pid, time.Now().Format(timeFormat)))
logx.Infof("Got dump goroutine signal, printing goroutine profile to %s", dumpFile)
2023-06-12 01:22:20 +08:00
if f, err := ctor.Create(dumpFile); err != nil {
2020-07-26 17:09:05 +08:00
logx.Errorf("Failed to dump goroutine profile, error: %v", err)
} else {
defer f.Close()
pprof.Lookup(goroutineProfile).WriteTo(f, debugLevel)
}
}
2023-06-12 01:22:20 +08:00
type fileCreator struct{}
func (fc fileCreator) Create(name string) (file *os.File, err error) {
return os.Create(name)
}