Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

put stack trace to string variable

Tags:

go

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.

like image 849
Maxim Yefremov Avatar asked Feb 10 '23 20:02

Maxim Yefremov


1 Answers

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.

like image 94
Bayta Darell Avatar answered Feb 13 '23 22:02

Bayta Darell