Go语言打印调用堆栈

来源:互联网 发布:java 自行车 编辑:程序博客网 时间:2024/06/08 00:24

这两天看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()}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

从上面代码可以看出,可以通过 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
原创粉丝点击