Home >Backend Development >Golang >How Can I Capture Stack Traces from Panics in Go?
Retrieving Stack Traces from Panics
Panics in Go generate valuable stack traces displayed on stdout. However, when recovering from a panic, only an error message is returned, limiting debugging capabilities.
This article explores the possibility of storing the panic's stack trace for enhanced debugging.
Solution: Utilizing the Runtime/Debug Package
As suggested by Volker and mentioned in the comments, Go's runtime/debug package provides the functionality to capture stack traces. Here's a code example demonstrating its usage:
package main import ( "fmt" "runtime/debug" ) func main() { // Define a deferred function to recover from the panic and store the stack trace. defer func() { if r := recover(); r != nil { stacktrace := string(debug.Stack()) fmt.Println("Stack trace from panic:\n", stacktrace) } }() // Panic with an out-of-range index access. var mySlice []int var index = 0 _, _ = mySlice[index] fmt.Println("This line will never run after the panic!") }
When you run this code, it prints the stack trace from the panic:
Stack trace from panic: goroutine 1 [running]: runtime/debug.Stack(0x1fd66a1e, 0x741000, 0x229080, 0xd92df0) /usr/lib/go/src/runtime/debug/stack.go:24 +0xc0 main.main.func1() /home/user/go/src/example.com/myapp/main.go:14 +0x60 panic(0x1feed5f8, 0xd92df0) /usr/lib/go/src/runtime/panic.go:562 +0x2c0 main.main() /home/user/go/src/example.com/myapp/main.go:20 +0x132
This output provides the line in the source code (main.go:14) that caused the panic, making it easier to identify the cause.
The above is the detailed content of How Can I Capture Stack Traces from Panics in Go?. For more information, please follow other related articles on the PHP Chinese website!