Skip to content

Instantly share code, notes, and snippets.

@TennyZhuang
Last active July 15, 2020 07:54
Show Gist options
  • Save TennyZhuang/1987e6750662331a3867cecf050536d2 to your computer and use it in GitHub Desktop.
Save TennyZhuang/1987e6750662331a3867cecf050536d2 to your computer and use it in GitHub Desktop.
A go function to create pure backtrace which can be used to aggregate traces.
package main
import (
"bytes"
"fmt"
"regexp"
"runtime/debug"
)
func f() {
g()
}
func g() {
h()
}
func h() {
fmt.Println(string(pureStack()))
}
func pureStack() []byte {
stack := debug.Stack()
lines := bytes.Split(stack, []byte{'\n'})[1:]
newLines := make([][]byte, len(lines))
r := regexp.MustCompile(`\(.*\)`)
for i := 0; i < len(lines); i++ {
line := lines[i]
if i % 2 == 1 {
newLines[i] = line
continue
}
line = r.ReplaceAll(line, []byte{})
newLines[i] = line
}
return bytes.Join(newLines, []byte{'\n'})
}
func main() {
f()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment