Skip to content

Commit

Permalink
Merge pull request #4 from DragonFlyBSD/fix-log
Browse files Browse the repository at this point in the history
common: Fix log functions to report correct filename and line info
  • Loading branch information
liweitianux authored Mar 31, 2023
2 parents 71f8458 + 385744a commit bd75375
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 bd75375

Please sign in to comment.