Skip to content

Instantly share code, notes, and snippets.

@thehowl
Last active January 15, 2024 21:59
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 thehowl/48834b1fa04ce10db8bca0684dc5c84c to your computer and use it in GitHub Desktop.
Save thehowl/48834b1fa04ce10db8bca0684dc5c84c to your computer and use it in GitHub Desktop.
a utility function to print compact stacktraces - https://go.dev/play/p/cAyTUqy1p_I
/* Sample output:
prog.go:11 main.main
proc.go:250 runtime.main
asm_amd64.s:1598 runtime.goexit
*/
package main
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
func main() {
smallStacktrace()
}
func smallStacktrace() string {
const unicodeEllipsis = "\u2026"
var buf bytes.Buffer
pc := make([]uintptr, 100)
pc = pc[:runtime.Callers(2, pc)]
frames := runtime.CallersFrames(pc)
for {
f, more := frames.Next()
if idx := strings.LastIndexByte(f.Function, '/'); idx >= 0 {
f.Function = f.Function[idx+1:]
}
// trim full path to at most 30 characters
fullPath := fmt.Sprintf("%s:%-4d", f.File, f.Line)
if len(fullPath) > 30 {
fullPath = unicodeEllipsis + fullPath[len(fullPath)-29:]
}
fmt.Fprintf(&buf, "%30s %s\n", fullPath, f.Function)
if !more {
return buf.String()
}
}
return buf.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment