Skip to content

Instantly share code, notes, and snippets.

@kovetskiy
Created November 18, 2020 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kovetskiy/0ee085b54a147c4e5eb1e6c83dca731e to your computer and use it in GitHub Desktop.
Save kovetskiy/0ee085b54a147c4e5eb1e6c83dca731e to your computer and use it in GitHub Desktop.
Go get stacktrace
func getStack(skip int) string {
buffer := make([]byte, 1024)
for {
written := runtime.Stack(buffer, false)
if written < len(buffer) {
// call stack contains of goroutine number and set of calls
// goroutine NN [running]:
// github.com/user/project.(*Type).MethodFoo()
// path/to/src.go:line
// github.com/user/project.MethodBar()
// path/to/src.go:line
// so if we need to skip 2 calls than we must split stack on
// following parts:
// 2(call)+2(call path)+1(goroutine header) + 1(callstack)
// and extract first and last parts of resulting slice
stack := strings.SplitN(string(buffer[:written]), "\n", skip*2+2)
return stack[0] + "\n" + stack[skip*2+1]
}
buffer = make([]byte, 2*len(buffer))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment