diff --git a/logger.go b/logger.go index 44f143f..7826a86 100644 --- a/logger.go +++ b/logger.go @@ -3,6 +3,8 @@ package main import ( "io" "log" + "runtime" + "strconv" c "github.com/fatih/color" ) @@ -16,24 +18,84 @@ type Logger interface { } type logger struct { - logger *log.Logger - printer *c.Color + logger *log.Logger + shortfile bool + printer *c.Color +} + +func Lshortfile() string { + _, file, line, ok := runtime.Caller(2) + lineString := strconv.Itoa(line) + if !ok { + return "" + } + if file == "" { + return lineString + } + for i := len(file) - 1; i > 0; i-- { + if file[i] == '/' || file[i] == '\\' { + file = file[i+1:] + break + } + } + return file + ":" + lineString + ":" } func NewLogger(out io.Writer, prefix string, flag int, color c.Attribute) (l logger) { + // Use reimplemented Lshortfile since wrapping the log functions messes them up + if flag&log.Lshortfile != 0 { + flag -= log.Lshortfile + l.shortfile = true + } + l.logger = log.New(out, prefix, flag) l.printer = c.New(color) return l } func (l logger) Printf(format string, v ...interface{}) { - l.logger.Print(l.printer.Sprintf(format, v...)) + var out string + if l.shortfile { + out = Lshortfile() + } + out += " " + l.printer.Sprintf(format, v...) + l.logger.Print(out) } -func (l logger) Print(v ...interface{}) { l.logger.Print(l.printer.Sprint(v...)) } -func (l logger) Println(v ...interface{}) { l.logger.Print(l.printer.Sprintln(v...)) } -func (l logger) Fatal(v ...interface{}) { l.logger.Fatal(l.printer.Sprint(v...)) } + +func (l logger) Print(v ...interface{}) { + var out string + if l.shortfile { + out = Lshortfile() + } + out += " " + l.printer.Sprint(v...) + l.logger.Print(out) +} + +func (l logger) Println(v ...interface{}) { + var out string + if l.shortfile { + out = Lshortfile() + } + out += " " + l.printer.Sprintln(v...) + l.logger.Print(out) +} + +func (l logger) Fatal(v ...interface{}) { + var out string + if l.shortfile { + out = Lshortfile() + } + out += " " + l.printer.Sprint(v...) + l.logger.Fatal(out) +} + func (l logger) Fatalf(format string, v ...interface{}) { - l.logger.Fatal(l.printer.Sprintf(format, v...)) + var out string + if l.shortfile { + out = Lshortfile() + } + out += " " + l.printer.Sprintf(format, v...) + l.logger.Fatal(out) } type emptyLogger bool