Go笔记 - panic 打印函数调用栈

4,640 阅读1分钟

程序异常退出时,查看函数调用栈是很重要的,能够帮助排查代码Bug。google了一下,做个笔记。

package main

import (
    "fmt"
    "runtime"
)

func main() {
    defer func() {
        if err := recover(); err != nil {
            const size = 64 << 10
            buf := make([]byte, size)
            buf = buf[:runtime.Stack(buf, false)]
            fmt.Println(string(buf))
        }   
    }() 
    panic("expect panic")
}