回答

收藏

如何转储 goroutine 堆栈跟踪?

技术问答 技术问答 296 人阅读 | 0 人回复 | 2023-09-12

我有 Java 背景,我喜欢使用信号 QUIT 来检查 Java 线程转储。
3 B7 m9 h+ J+ f. M/ J9 f& w  q如何让 Golang 打印所有 goroutine 堆栈跟踪?
- F* t5 Q1 V2 P  [: ?1 T' ?                                                               
3 ?0 a0 r' z9 w" b) A" c  y    解决方案:                                                                + K; C* \) U$ L0 V! P9 y
                                                                要打印当前goroutine请使用堆栈跟踪PrintStack()fromruntime/debug。
" l: k/ f8 j) _+ ]7 c3 a+ RPrintStack 将 Stack 返回的堆栈跟踪打印到标准错误。
; {. Q& D5 I! h7 a0 D例如:
8 f! a  A7 x) Q" w" c9 y
    import(   "runtime/debug")...    debug.PrintStack()" ~; U: s! L$ L9 A9 {
要打印所有goroutine请使用堆栈跟踪Lookup和WriteTofrom runtime/pprof。
) K+ e: A/ ~" X+ @9 r& {! D- z, W
    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." Z7 I: ?- k9 T, Q( H8 Z7 j+ K
每个配置文件都有一个独特的名称。预定义了一些配置文件:$ k3 C- Z  X# i& @! ?
goroutine - 所有当前 goroutine 堆栈跟踪7 `- r4 g4 M2 t# ^5 }( ~7 n$ Y
heap - 所有堆分配
8 v' _& F# m! \4 [% r样本 threadcreate - 导致创建新操作系统线程
5 c8 w: m5 U) A* R3 G8 M堆栈跟踪 block - 同步原语阻塞的堆栈跟踪% I5 t7 |; S  K3 ]
例如:
5 W0 W3 o  p+ {8 y: W/ k
    pprof.Lookup("goroutine").WriteTo(os.Stdout,1)1 P; \1 \4 l' H7 z& n
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则