【Golang】打印调用栈信息

Posted by 西维蜀黍 on 2021-02-17, Last Modified on 2021-09-21

debug.Stack() - 打印当前 goroutine 的堆栈

package main

import (
	"fmt"
	"runtime/debug"
)

func test1() {
	test2()
}

func test2() {
	test3()
}

func test3() {
	fmt.Printf("%s", debug.Stack())
	//debug.PrintStack() // equivalent to the above
}

func main() {
	test1()
}
goroutine 1 [running]:
runtime/debug.Stack(0x10ecf40, 0x4, 0xc00007ef20)
        /usr/local/go/src/runtime/debug/stack.go:24 +0x9d
main.test3()
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:17 +0x26
main.test2(...)
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:13
main.test1(...)
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:9
main.main()
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:22 +0x22

runtime.Stack() - 打印所有 goroutines 的堆栈

package main

import (
	"fmt"
	"runtime"
)

func test1() {
	test2()
}
func test2() {
	test3()
}
func test3() {
	fmt.Printf("%s", allGoroutineStacks())
}
func test4() {
	test5()
}
func test5() {
	for {
		fmt.Print("aaa\n")
	}
}

func main() {
	go test4()
	test1()
}

func allGoroutineStacks() []byte {
	buf := make([]byte, 1024)
	for {
		n := runtime.Stack(buf, true)
		if n < len(buf) {
			return buf[:n]
		}
		buf = make([]byte, 2*len(buf))
	}
}
goroutine 1 [running]:
main.allGoroutineStacks(0x10d6086, 0x1d, 0x10ed400)
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:37 +0x9d
main.test3()
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:17 +0x26
main.test2(...)
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:13
main.test1(...)
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:9
main.main()
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:31 +0x3c

goroutine 18 [runnable]:
main.test4()
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:21
created by main.main
        /Users/wei.shi/Working/GoPlayGround/sw_pprof/sw_pprof.go:30 +0x35

Reference