Reputation: 14175
Is it possible to put stack trace like this ...
goroutine 20 [running]:
runtime.panic(0x3a2820, 0xc2081ad4b0)
/usr/local/go/src/pkg/runtime/panic.c:279 +0xf5
testing.func·006()
/usr/local/go/src/pkg/testing/testing.go:416 +0x176
runtime.panic(0x3a2820, 0xc2081ad4b0)
/usr/local/go/src/pkg/runtime/panic.c:248 +0x18d
my.Test(0x3a2820, 0xc2081acf20, 0x3a2820, 0xc2081acf30, 0xc208056000)
/Users/usr/golang/src/my/testing.go:67 +0x572
... in string variable for reformating it and cut off redundunt information for me.
This pseudo code would be like this:
package main
import (
"runtime"
)
func main() {
var stackStr string
stackStr = runtime.GetStackFromHere()
}
I tried panic("give me stack trace from here")
but it prints stack trace not in var string
but only to console.
Upvotes: 6
Views: 1706
Reputation: 120979
Use the runtime.Stack function to get the stack trace:
b := make([]byte, 2048) // adjust buffer size to be larger than expected stack
n := runtime.Stack(b, false)
s := string(b[:n])
An alternative approach is to call runtime.Caller in a loop and format the stack trace to a buffer.
Upvotes: 10