Last active
January 15, 2024 21:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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