我有Java背景,我喜欢使用信号QUIT来判断Java线程转储.

如何让Golang打印出所有的Goroutine堆栈痕迹?

推荐答案

要打印current goroutine的堆栈跟踪,请使用PrintStack() from runtime/debug.

PrintStack将stack返回的堆栈跟踪打印为标准错误.

例如:

import(
   "runtime/debug"
)
...    
debug.PrintStack()

要打印all个goroutine的堆栈跟踪,请使用runtime/pprof中的LookupWriteTo.

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-导致创建新操作系统线程的堆栈跟踪
导致同步基元阻塞的挡路堆栈跟踪

例如:

pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)

Go相关问答推荐

Go - os.userHomeDir()在WSL上返回C:\Users\

将Go程序导出到WASM—构建约束排除所有Go文件

运行add. inf,这样我们就可以在app.conf中使用. inf参数了?

Zitadel示例Go Webapp加密密钥

Go在使用HTTP代理时如何处理DNS请求?

如何在Golang中获取mp3文件的持续时间?

允许在 struct 中使用复合作为函数参数

如何模拟 stripe 需要 webhooks 的捕获事件?

Caddy服务器try 打开端口80而不是8090.

动态 SQL 集 Golang

使用 os/exec 和在命令行执行之间的结果莫名其妙地不同

为什么互斥量比 golang 中的通道慢?

如何将一片 map 转换为一片具有不同属性的 struct

如何使用 go-playground/validator 编写 snake case 绑定标签?

golang pic.ShowImage 为什么它不生成图像而是向我发送base64值

从 Makefile 运行时权限被拒绝

如何在 golang 中同时加载 .env 文件和 os 环境变量

Go 并发、goroutine 同步和关闭通道

将未知长度切片的值分配给Go中的 struct ?

将基本 HTTP AUth 用户/密码凭据存储在 GO 中,无需外部包