Go语言打印调用堆栈


Go语言打印调用堆栈

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

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

package main

import (
    "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.go

goroutine 1 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80
main.test3()
        /tmp/test_stacktrace.go:17 +0x24
main.test2()
        /tmp/test_stacktrace.go:13 +0x14
main.test1()
        /tmp/test_stacktrace.go:9 +0x14
main.main()
        /tmp/test_stacktrace.go:22 +0x14

goroutine 1 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80
runtime/debug.PrintStack()
        /usr/lib/golang/src/runtime/debug/stack.go:16 +0x18
main.test3()
        /tmp/test_stacktrace.go:18 +0x101
main.test2()
        /tmp/test_stacktrace.go:13 +0x14
main.test1()
        /tmp/test_stacktrace.go:9 +0x14
main.main()
        /tmp/test_stacktrace.go:22 +0x14


原文链接:https://blog.csdn.net/kongxx/article/details/76167000?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163599231616780274182818%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=163599231616780274182818&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v29-15-76167000.pc_v2_rank_blog_default&utm_term=go&spm=1018.2226.3001.4450