我有Java背景,并且喜欢使用信号QUIT检查Java线程转储。
如何让Golang打印出所有goroutine堆栈跟踪?
要打印 当前 goroutine
的堆栈跟踪,请使用PrintStack()
fromruntime/debug
。
PrintStack将Stack返回的堆栈跟踪打印到标准错误。
例如:
import(
"runtime/debug"
)
...
debug.PrintStack()
要打印 所有 goroutine
的堆栈跟踪,请使用Lookup
和WriteTo
从runtime/pprof
。
func Lookup(name string) *Profile
// Lookup returns the profile with the given name,
// or nil if no such profile exists.
func (p *Profile) WriteTo(w io.Writer, debug int) error
// WriteTo writes a pprof-formatted snapshot of the profile to w.
// If a write to w returns an error, WriteTo returns that error.
// Otherwise, WriteTo returns nil.
每个配置文件都有一个唯一的名称。预定义了一些配置文件:
goroutine-当前所有goroutine
堆的堆栈跟踪-所有堆分配的采样
threadcreate-导致创建新OS线程
块的堆栈跟踪-导致对同步原语进行阻塞的堆栈跟踪
例如:
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)