From 7dab6e0054d7ea9c7e325445b0bdde90571d4038 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Mon, 22 Apr 2019 14:45:23 +0200 Subject: [PATCH] call stack for error tracing --- main.go | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 52ae753..230e51d 100644 --- a/main.go +++ b/main.go @@ -89,19 +89,32 @@ func (l *Logger) Print(format string, v ...interface{}) { fmt.Printf("%s: %s\n", time.Now().Format(dateTimeFormat), msg) } -// CallerFilenameAndLineNumber ... -func CallerFilenameAndLineNumber() (string, int) { - _, path, line, _ := runtime.Caller(2) - file := filepath.Base(path) - return file, line +const MaxStackDepth = 10000 + +// CallStack +func CallStack() (stack string) { + callers := make([]uintptr, MaxStackDepth) // min 1 + stackDepth := runtime.Callers(2, callers) + frames := runtime.CallersFrames(callers) + + for i := 0; i < stackDepth; i++ { + if i >= 2 { // skip runtime and startup + frame, next := frames.Next() + stack += fmt.Sprintf("[%s %d]\n", frame.File, frame.Line) + if !next { + break + } + } + } + + return } // PrintTrace ... func (l *Logger) PrintTrace(format string, v ...interface{}) { - file, line := CallerFilenameAndLineNumber() - + stack := CallStack() msg := fmt.Sprintf(format, v...) - fmt.Printf("%s: %s %d: %s\n", time.Now().Format(dateTimeFormat), file, line, msg) + fmt.Printf("%s:\n%s\n%s\n", time.Now().Format(dateTimeFormat), stack, msg) } // Trace ... @@ -113,10 +126,10 @@ func (l *Logger) Trace(format string, v ...interface{}) { l.mu.Lock() defer l.mu.Unlock() - file, line := CallerFilenameAndLineNumber() + stack := CallStack() msg := fmt.Sprintf(format, v...) - s := fmt.Sprintf("%s: %s %d: %s\n", time.Now().Format(dateTimeFormat), file, line, msg) + s := fmt.Sprintf("%s:\n%s\n%s\n", time.Now().Format(dateTimeFormat), stack, msg) if l.shouldSplit(len(s)) { l.split() -- 1.8.1.2