Home >Backend Development >Golang >How Can I Capture and Store the Stack Trace of a Panic in Go?

How Can I Capture and Store the Stack Trace of a Panic in Go?

DDD
DDDOriginal
2024-11-15 17:07:02617browse

How Can I Capture and Store the Stack Trace of a Panic in Go?

Retrieving and Storing Panic Stack Traces

When a panic occurs in a Go program, a stack trace providing valuable debugging information is automatically printed to standard output. However, when recovering from a panic, recover() only returns an error string indicating the cause of the panic.

This raises the question of whether it's possible to store the printed stack trace for further analysis.

Solution: Utilizing the Runtime/Debug Package

To address this issue, we can leverage the runtime/debug package. By wrapping our code in a deferred function that invokes recover(), we can capture the panic and access the stack trace using debug.Stack().

Below is an example code snippet showcasing this approach:

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)
}

When run, this code will output the following stack trace upon panicking:

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

This stack trace provides a detailed view of the function call chain leading up to the panic, making it easier to pinpoint the source of the error.

The above is the detailed content of How Can I Capture and Store the Stack Trace of a Panic in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn