gtristan
gtristan

Reputation: 445

Splitting traceback stack into structure in go

I'm looking for a way to write to log a traceback stack in golang, but only some lines from it. As I see it, it could be done by splitting the result obtained from debug.Stack() into a slice of structures, which could be then easily parsed.

this is what I get now with this call "fmt.Println(string(debug.Stack()))":

goroutine 1 [running]:
runtime/debug.Stack(0xc0000c0050, 0x2, 0x0)
        /go/go1.15rc1/src/runtime/debug/stack.go:24 +0x9f
main.go_logger(0x4cc235, 0x11, 0x4ccf9d, 0x15, 0xc000090101)
        /go/src/ethernet_monitor/info.go:30 +0x290
main.temp(...)
        /go/src/ethernet_monitor/info.go:40
main.main()
        /go/src/ethernet_monitor/info.go:45 +0x52

and that is the way I want it to be split, similar to python's traceback.extract_stack() structure:

fileName: /go/src/ethernet_monitor/info.go
function: main.main()
lineNumber: 45

So the question is - is it implemented somehow already? I'm not very confident writing my own parsing function as I might miss some specific cases.

Upvotes: 3

Views: 820

Answers (1)

TehSphinX
TehSphinX

Reputation: 7430

You are probably better off using runtime.Callers to get the individual items rather than trying to parse the stack as bytes.

This is what github.com/pkg/errors does here: https://github.com/pkg/errors/blob/master/stack.go#L163:1. You can see that runtime.Callers is already capable of skipping some levels.

From the uintptr needed you can see, this is quite low level. You should however be fine just copying callers function and all it depends on over and use the StackTrace function to get a more usable stack of individual Frames: https://github.com/pkg/errors/blob/master/stack.go#L155

The frames can then be enhanced to return the function name, file, line number etc. How to extract that information can be seen in the different private functions of the Frame: https://github.com/pkg/errors/blob/master/stack.go#L23

I've done the same in our local errors package to be able to adjust how the stack is printed. This can be adjusted in the Format function of a Frame.

Note: maybe not the simplest solution as this exposes you to some low level stuff, but I'd prefer it anytime over parsing the already printed stack.

Upvotes: 3

Related Questions