回答

收藏

如何转储 goroutine 堆栈跟踪?

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

我有 Java 背景,我喜欢使用信号 QUIT 来检查 Java 线程转储。
4 o4 P/ [" I$ q  G% W" n如何让 Golang 打印所有 goroutine 堆栈跟踪?$ T* B2 p0 w& C
                                                               
, @9 M, B# N. N( K4 }    解决方案:                                                               
( _6 y. v( _) S) X                                                                要打印当前goroutine请使用堆栈跟踪PrintStack()fromruntime/debug。
) \  _( |( _: t  D' NPrintStack 将 Stack 返回的堆栈跟踪打印到标准错误。
- {1 e* n* B0 Q" ~; ^例如:
9 g& f2 M* M* S" c# R8 S* [
    import(   "runtime/debug")...    debug.PrintStack()  K% j6 z+ X4 J
要打印所有goroutine请使用堆栈跟踪Lookup和WriteTofrom runtime/pprof。
; I' V% p  \% S4 K8 P
    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.
    1 y4 n. A; C+ |* Y
每个配置文件都有一个独特的名称。预定义了一些配置文件:
: B/ _& h4 }' h2 t( ngoroutine - 所有当前 goroutine 堆栈跟踪3 f$ Z  M6 F' `1 c0 `0 i
heap - 所有堆分配6 e1 p4 A3 i2 ]) ^5 f; I" n
样本 threadcreate - 导致创建新操作系统线程! y0 ]; q6 ^' {
堆栈跟踪 block - 同步原语阻塞的堆栈跟踪( L: H6 O% w2 }8 J, [7 D) }8 t
例如:
3 h8 L% S- v4 g3 N0 I# J
    pprof.Lookup("goroutine").WriteTo(os.Stdout,1)
    . t0 {9 `: n# V2 ]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则