Skip to content

Instantly share code, notes, and snippets.

@luxarts
Created August 12, 2021 17:03
Show Gist options
  • Save luxarts/cd48a2f3b16f23d35e7b79bc9c66f7c1 to your computer and use it in GitHub Desktop.
Save luxarts/cd48a2f3b16f23d35e7b79bc9c66f7c1 to your computer and use it in GitHub Desktop.
Golang stacktrace
func getStackTrace() string {
// Method stack trace
pc := make([]uintptr, 10) // Last traces
n := runtime.Callers(2, pc) // Discard first (callers) and second (this function) values
if n == 0 {
return ""
}
pc = pc[:n] // Apply some magic
frames := runtime.CallersFrames(pc) // Get all callers
var calls []runtime.Frame
// Iterate over calls
for {
frame, more := frames.Next() // Get next call
if !more {
break
}
calls = append(calls, frame) // Save the call
}
var b strings.Builder
// Build string
for i := len(calls) - 2; i > 0; i-- {
b.WriteString(fmt.Sprintf("%v > ", calls[i].Function))
}
b.WriteString(fmt.Sprintf("%v ", calls[0].Function))
b.WriteString(fmt.Sprintf("in %s at line %d.\n", calls[0].File, calls[0].Line))
// Write string in log
return b.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment