Skip to content

Commit

Permalink
common: Fix log functions to report correct filename and line info
Browse files Browse the repository at this point in the history
The log functions wrap around Go's builtin 'log' module.  While the
latter reports the filename and line where the log messages emit,
they were always the file 'log.go' and lines in it.

So implement the 'getOrigin()' function to obtain the real caller info
by our own.  In addition, obtain the function name of the caller and
report in the log messages.

Credit: https://stackoverflow.com/a/58232098
  • Loading branch information
liweitianux committed Mar 31, 2023
1 parent 71f8458 commit 385744a
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions common/log.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package common

import (
"fmt"
"log"
"os"
"runtime"
"strconv"
"strings"
)

var (
Expand All @@ -11,30 +15,51 @@ var (
)

func init() {
flag := log.Ldate|log.Ltime|log.Lshortfile
flag := log.Ldate|log.Ltime
outLogger = log.New(os.Stdout, "", flag)
errLogger = log.New(os.Stderr, "", flag)
}

// Get the file and function information of the logger caller.
// Result: "filename:line:function"
func getOrigin() string {
// calldepth is 2: caller -> xxxPrintf() -> getOrigin()
pc, file, line, ok := runtime.Caller(2)
if !ok {
return "???:0:???"
}

filename := file[strings.LastIndex(file, "/")+1:]
funcname := runtime.FuncForPC(pc).Name()
fn := funcname[strings.LastIndex(funcname, ".")+1:]
return filename + ":" + strconv.Itoa(line) + ":" + fn
}

func DebugPrintf(format string, v ...interface{}) {
if !AppConfig.Debug {
return
}
errLogger.Printf("[DEBUG] " + format, v...)

format = fmt.Sprintf("[DEBUG] %s: %s", getOrigin(), format)
errLogger.Printf(format, v...)
}

func InfoPrintf(format string, v ...interface{}) {
outLogger.Printf("[INFO] " + format, v...)
format = fmt.Sprintf("[INFO] %s: %s", getOrigin(), format)
outLogger.Printf(format, v...)
}

func WarnPrintf(format string, v ...interface{}) {
errLogger.Printf("[WARNING] " + format, v...)
format = fmt.Sprintf("[WARNING] %s: %s", getOrigin(), format)
errLogger.Printf(format, v...)
}

func ErrorPrintf(format string, v ...interface{}) {
errLogger.Printf("[ERROR] " + format, v...)
format = fmt.Sprintf("[ERROR] %s: %s", getOrigin(), format)
errLogger.Printf(format, v...)
}

func Fatalf(format string, v ...interface{}) {
errLogger.Fatalf("[FATAL] " + format, v...)
format = fmt.Sprintf("[FATAL] %s: %s", getOrigin(), format)
errLogger.Fatalf(format, v...)
}

0 comments on commit 385744a

Please sign in to comment.