Skip to content

Instantly share code, notes, and snippets.

@timonwong
Created July 21, 2014 06:28
Show Gist options
  • Save timonwong/b81153e3b0bec6e4356e to your computer and use it in GitHub Desktop.
Save timonwong/b81153e3b0bec6e4356e to your computer and use it in GitHub Desktop.
Go stack trace
package main
import (
"fmt"
"runtime"
)
func StackTrace(all bool) string {
// Reserve 10K buffer at first
buf := make([]byte, 10240)
for {
size := runtime.Stack(buf, all)
// The size of the buffer may be not enough to hold the stacktrace,
// so double the buffer size
if size == len(buf) {
buf = make([]byte, len(buf)<<1)
continue
}
break
}
return string(buf)
}
func main() {
fmt.Println("=== CURRENT GOROUTINE STACKTRACE ===")
fmt.Println(StackTrace(false))
fmt.Println("=== ALL GOROUTINES STACKTRACE ===")
fmt.Println(StackTrace(true))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment