dro59505 2018-08-30 18:18
浏览 32
已采纳

如何获取紧急情况的堆栈跟踪(并存储为变量)

As we all know, panics produce a stacktrace to stdout (Playground link).:

panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
    /tmp/sandbox579134920/main.go:9 +0x20

And it seems when you recover from a panic, recover() returns only an error which describes what caused the panic (Playground link).

runtime error: index out of range

My question is, is it possible to store the stacktrace which is written to stdout? This provides much better debugging information than the string runtime error: index out of range because it shows the exact line in a file which caused the panic.

  • 写回答

2条回答 默认 最新

  • duai1683 2018-08-30 22:51
    关注

    Like @Volker mentioned above, and what was posted as a comment, we can use the runtime/debug package.

    package main
    
    import (
        "fmt"
        "runtime/debug"
    )
    
    func main() {
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("stacktrace from panic: 
    " + string(debug.Stack()))
            }
        }()
    
        var mySlice []int
        j := mySlice[0]
    
        fmt.Printf("Hello, playground %d", j)
    }
    

    prints

    stacktrace from panic: 
    goroutine 1 [running]:
    runtime/debug.Stack(0x1042ff18, 0x98b2, 0xf0ba0, 0x17d048)
        /usr/local/go/src/runtime/debug/stack.go:24 +0xc0
    main.main.func1()
        /tmp/sandbox973508195/main.go:11 +0x60
    panic(0xf0ba0, 0x17d048)
        /usr/local/go/src/runtime/panic.go:502 +0x2c0
    main.main()
        /tmp/sandbox973508195/main.go:16 +0x60
    

    Playground link.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看