How to get the stacktrace of a panic (and store as a variable)

Like @Volker mentioned above, and what was posted as a comment, we can use the runtime/debug package.

package main

import (

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
    /tmp/sandbox973508195/main.go:11 +0x60
panic(0xf0ba0, 0x17d048)
    /usr/local/go/src/runtime/panic.go:502 +0x2c0
    /tmp/sandbox973508195/main.go:16 +0x60

Playground link.

Leave a Comment