我有 Java 背景,我喜欢使用信号 QUIT 来检查 Java 线程转储.
如何让 Golang 打印出所有的 goroutine 堆栈跟踪?
解决方案要打印 current goroutine 的堆栈跟踪,请使用 PrintStack() 来自 runtime/debug.
PrintStack 将 Stack 返回的堆栈跟踪打印到标准错误.
例如:
import(运行时/调试")...调试.PrintStack()要打印所有 goroutine 的堆栈跟踪,请使用 查找和WriteTo 来自 runtime/pprof.
func Lookup(name string) *Profile//查找返回具有给定名称的配置文件,//如果不存在这样的配置文件,则为 nil.func (p *Profile) WriteTo(w io.Writer, debug int) 错误//WriteTo 将配置文件的 pprof 格式的快照写入 w.//如果写入 w 返回错误,WriteTo 返回该错误.//否则,WriteTo 返回 nil.每个配置文件都有一个唯一的名称.一些配置文件是预定义的:
goroutine - 所有当前 goroutine 的堆栈跟踪堆 - 所有堆分配的抽样threadcreate - 导致创建新操作系统线程的堆栈跟踪block - 导致同步原语阻塞的堆栈跟踪
例如:
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)I have Java background, and I love to use signal QUIT to inspect Java thread dump.
How to let Golang print out all goroutines stack trace?
解决方案To print the stack trace for the current goroutine, use PrintStack() from runtime/debug.
PrintStack prints to standard error the stack trace returned by Stack.
For example:
import( "runtime/debug" ) ... debug.PrintStack()To print the stack trace for all goroutines use Lookup and WriteTo from 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.
Each Profile has a unique name. A few profiles are predefined:
goroutine - stack traces of all current goroutines heap - a sampling of all heap allocations threadcreate - stack traces that led to the creation of new OS threads block - stack traces that led to blocking on synchronization primitives
For example:
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
更多推荐
如何转储 goroutine 堆栈跟踪?
发布评论