回答

收藏

如何转储 goroutine 堆栈跟踪?

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

我有 Java 背景,我喜欢使用信号 QUIT 来检查 Java 线程转储。
' {' w% `/ Y! Y( `: B如何让 Golang 打印所有 goroutine 堆栈跟踪?+ k- ~! F* e# T+ q9 k: q& {* C) r( O9 U
                                                                6 R* v) H7 f) q: Y( o) ^
    解决方案:                                                               
9 p4 D# a. y# F! J                                                                要打印当前goroutine请使用堆栈跟踪PrintStack()fromruntime/debug。
/ U5 A' ~5 d+ Z5 H6 ?1 E9 N4 \+ C# mPrintStack 将 Stack 返回的堆栈跟踪打印到标准错误。0 b$ z' b: U6 @) p* v0 w
例如:: i! d* O$ r+ ]# x& E+ a. L
    import(   "runtime/debug")...    debug.PrintStack()
    ! K; w$ s' K) J' q: p' `: D  a
要打印所有goroutine请使用堆栈跟踪Lookup和WriteTofrom runtime/pprof。
& X  p. l: e2 ~& W- u
    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.
    $ O" a# _2 ~2 f/ s, h
每个配置文件都有一个独特的名称。预定义了一些配置文件:- ]) n* d$ S' j6 H
goroutine - 所有当前 goroutine 堆栈跟踪$ s: r5 N+ y  H" V
heap - 所有堆分配
+ O, j8 Z4 S! B5 X样本 threadcreate - 导致创建新操作系统线程
6 J5 |, w- O( a; T/ F" X堆栈跟踪 block - 同步原语阻塞的堆栈跟踪
) l# T4 J1 m  A) E: Z! {9 A. t例如:4 Q( I; R: F$ u8 V* t- |
    pprof.Lookup("goroutine").WriteTo(os.Stdout,1)
    + r' Y2 l8 I9 k. {% Z6 m
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则