如何转储 goroutine 堆栈跟踪? [英] How to dump goroutine stacktraces?

查看:37
本文介绍了如何转储 goroutine 堆栈跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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 堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆