Created
September 26, 2022 19:30
-
-
Save scottcagno/fc6112d1fbef949ff2abf1c64210b3a8 to your computer and use it in GitHub Desktop.
Stack tracer
This file contains hidden or 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
| package tracer | |
| import ( | |
| "fmt" | |
| "log" | |
| "runtime" | |
| "strings" | |
| ) | |
| // DefaultTracer is the default tracer and has a call | |
| // depth of 3, which works in most situations for me. | |
| var DefaultTracer = NewTracer(3) | |
| type Tracer struct { | |
| Depth int | |
| } | |
| // You may need to adjust the calldepth to get the proper | |
| // resolution on the traces, depending on where the tracer | |
| // is initialized and situated within your project. Usually | |
| // the correct call depth can be found between 2, and 6. | |
| func NewTracer(depth int) *Tracer { | |
| return &Tracer{ | |
| Depth: depth, | |
| } | |
| } | |
| func (t *Tracer) String() string { | |
| pc := make([]uintptr, 10) // at least 1 entry needed | |
| runtime.Callers(t.Depth, pc) | |
| f := runtime.FuncForPC(pc[0]) | |
| file, line := f.FileLine(pc[0]) | |
| sfile := strings.Split(file, "/") | |
| sname := strings.Split(f.Name(), "/") | |
| return fmt.Sprintf("[%s:%d %s]", sfile[len(sfile)-1], line, sname[len(sname)-1]) | |
| } | |
| func (t *Tracer) Panic(err error) { | |
| log.Panicf("%s (errType=%T, err=%q)", t, err, err) | |
| } | |
| func (t *Tracer) Log(err error) { | |
| log.Printf("%s (errType=%T, err=%q)", t, err, err) | |
| } | |
| func (t *Tracer) Logln(err error) { | |
| log.Printf("%s (errType=%T, err=%q)\n", t, err, err) | |
| } | |
| func (t *Tracer) Logf(format string, v ...interface{}) { | |
| log.Printf(t.String()+" "+format, v...) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment