Go语言打印调用堆栈

来源:互联网 发布:台湾庄园知乎 编辑:程序博客网 时间:2024/06/05 18:01

Go语言打印调用堆栈

这两天看Go的代码,呃,协程太多,无数个携程调用了一个方法,彻底看不清了,所以就想到是不是可以把调用堆栈打印出来。

查了一下,发现Go的 runtime/debug 库可以把调用堆栈打出来。下面看个例子:

package mainimport (    "fmt"    "runtime/debug")func test1() {    test2()}func test2() {    test3()}func test3() {    fmt.Printf("%s", debug.Stack())    debug.PrintStack()}func main() {    test1()}

从上面代码可以看出,可以通过 debug.PrintStack() 直接打印,也可以通过 debug.Stack() 方法获取堆栈然后自己打印。

运行测试

$ go run test_stacktrace.gogoroutine 1 [running]:runtime/debug.Stack(0x0, 0x0, 0x0)        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80main.test3()        /tmp/test_stacktrace.go:17 +0x24main.test2()        /tmp/test_stacktrace.go:13 +0x14main.test1()        /tmp/test_stacktrace.go:9 +0x14main.main()        /tmp/test_stacktrace.go:22 +0x14goroutine 1 [running]:runtime/debug.Stack(0x0, 0x0, 0x0)        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80runtime/debug.PrintStack()        /usr/lib/golang/src/runtime/debug/stack.go:16 +0x18main.test3()        /tmp/test_stacktrace.go:18 +0x101main.test2()        /tmp/test_stacktrace.go:13 +0x14main.test1()        /tmp/test_stacktrace.go:9 +0x14main.main()        /tmp/test_stacktrace.go:22 +0x14