Home  >  Article  >  Backend Development  >  How can I capture and store stacktraces from panics in Go?

How can I capture and store stacktraces from panics in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 17:27:02621browse

How can I capture and store stacktraces from panics in Go?

Retrieving and Storing Stacktraces from Panics

While panics generate informative stacktraces to standard output, the information may be lost when recovering from the panic using recover(). However, it is possible to capture and store the stacktrace for enhanced debugging.

The runtime/debug package offers a solution for retrieving stacktraces. Here's how it can be utilized:

package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    // Function to recover from panics and capture stacktraces
    defer func() {
        if r := recover(); r != nil {
            // Convert the stacktrace bytes into a string
            fmt.Println("Stacktrace from panic: \n" + string(debug.Stack()))
        }
    }()

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

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

This solution prints the following stacktrace:

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

By leveraging the runtime/debug package, you can effectively capture and store stacktraces, enabling more comprehensive debugging when panics occur in your Go applications.

The above is the detailed content of How can I capture and store stacktraces from panics 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