如何获取紧急情况的堆栈跟踪(并存储为变量) [英] How to get the stacktrace of a panic (and store as a variable)
问题描述
众所周知,恐慌会向标准输出产生堆栈跟踪(游乐场链接) 。:
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
似乎当您从恐慌中恢复时, recover()
仅返回一个错误
来描述引起恐慌的原因(< a href = https://play.golang.org/p/7qsB3F2klUb rel = noreferrer>游乐场链接)。
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
我的问题是,是否可以存储写到stdout的stacktrace?比字符串运行时错误:索引超出范围
,它提供了更好的调试信息,因为它显示了引起恐慌的文件中的确切行。
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.
推荐答案
就像上面提到的@Volker一样,以及作为注释发布的内容,我们可以使用 runtime / debug
包。
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: \n" + string(debug.Stack()))
}
}()
var mySlice []int
j := mySlice[0]
fmt.Printf("Hello, playground %d", j)
}
打印
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
这篇关于如何获取紧急情况的堆栈跟踪(并存储为变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!