diff --git a/debug/debug.go b/debug/debug.go index 55a47198c..a77cb3836 100644 --- a/debug/debug.go +++ b/debug/debug.go @@ -7,7 +7,9 @@ import ( "log" "os" "path" + "path/filepath" "runtime" + "strconv" "strings" "sync" "syscall" @@ -122,6 +124,30 @@ func initDebugBreaks() { fmt.Fprintf(os.Stderr, "debug breaks enabled for: %v\n", breaks) } +// taken from https://github.com/VividCortex/trace +func goroutineNum() int { + b := make([]byte, 20) + runtime.Stack(b, false) + var num int + + fmt.Sscanf(string(b), "goroutine %d ", &num) + return num +} + +// taken from https://github.com/VividCortex/trace +func getPosition() string { + _, file, line, ok := runtime.Caller(2) + if !ok { + return "" + } + + goroutine := goroutineNum() + + return fmt.Sprintf("%3d %s:%3d", goroutine, filepath.Base(file), line) +} + +var maxTagLen = 10 + func Log(tag string, f string, args ...interface{}) { opts.m.Lock() defer opts.m.Unlock() @@ -130,12 +156,19 @@ func Log(tag string, f string, args ...interface{}) { f += "\n" } + if len(tag) > maxTagLen { + maxTagLen = len(tag) + } + + formatStringTag := "[%" + strconv.FormatInt(int64(maxTagLen), 10) + "s]" + formatString := fmt.Sprintf(formatStringTag+" %s %s", tag, getPosition(), f) + dbgprint := func() { - fmt.Fprintf(os.Stderr, "DEBUG["+tag+"]: "+f, args...) + fmt.Fprintf(os.Stderr, formatString, args...) } if opts.logger != nil { - opts.logger.Printf("["+tag+"] "+f, args...) + opts.logger.Printf(formatString, args...) } // check if tag is enabled directly