Home >Backend Development >Golang >How to Store Panic Stacktraces in Go?

How to Store Panic Stacktraces in Go?

DDD
DDDOriginal
2024-11-19 16:14:02560browse

How to Store Panic Stacktraces in Go?

Retrieving and Storing Panic Stacktraces

Panics in Go produce valuable stacktraces that provide debugging insights. However, recovering from a panic only returns an error message that lacks detailed line-level information.

To address this limitation, the runtime/debug package offers a solution. Here's how you can store the stacktrace from a panic as a variable:

package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    defer func() {
        if r := recover(); r != nil {
            stacktrace := string(debug.Stack())
            fmt.Println("Stacktrace from panic:", stacktrace)
        }
    }()

    var mySlice []int
    j := mySlice[0] // panic

    fmt.Printf("Hello, playground %d", j) // unreachable code
}

Output:

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

This code demonstrates how to capture the stacktrace in the event of a panic, providing line-by-line details that facilitate effective debugging.

The above is the detailed content of How to Store Panic Stacktraces 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