回答

收藏

如何转储 goroutine 堆栈跟踪?

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

我有 Java 背景,我喜欢使用信号 QUIT 来检查 Java 线程转储。7 s: h& e/ Q: ^, K& b  t
如何让 Golang 打印所有 goroutine 堆栈跟踪?
* _. L2 x+ j! J6 G0 T                                                               
8 j' f6 Z% t0 R& r; D& N# \; }) {    解决方案:                                                                2 r7 e3 j; v0 \" Z0 Q! u
                                                                要打印当前goroutine请使用堆栈跟踪PrintStack()fromruntime/debug。
' E8 r" j$ g- o2 IPrintStack 将 Stack 返回的堆栈跟踪打印到标准错误。
. n3 T2 A: u4 n' P例如:1 i1 l& J! C' |8 ~- \
    import(   "runtime/debug")...    debug.PrintStack()
    7 @. Y6 y: L1 ]" m  Z
要打印所有goroutine请使用堆栈跟踪Lookup和WriteTofrom runtime/pprof。2 ?1 c5 V7 y8 h! R/ K2 h" @
    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.9 x' T* H! y3 K- L4 s* Y
每个配置文件都有一个独特的名称。预定义了一些配置文件:
: w+ {+ D, p- |  pgoroutine - 所有当前 goroutine 堆栈跟踪$ Q( s: E# V9 d
heap - 所有堆分配
5 ]. q; ?1 u/ M; L样本 threadcreate - 导致创建新操作系统线程
" [; c, g& R; [) {* V堆栈跟踪 block - 同步原语阻塞的堆栈跟踪
# A; D% U+ Y7 Q! R- r4 z2 C' ?例如:% s" V$ ]! O% J! f5 L
    pprof.Lookup("goroutine").WriteTo(os.Stdout,1)
    , ]2 N/ A7 M, a: q! V
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则