Add a logger that auto-includes file+callsite
This commit is contained in:
42
logger/logger.go
Normal file
42
logger/logger.go
Normal file
@ -0,0 +1,42 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// logf logs a message with automatic caller information (file:function)
|
||||
func logf(format string, args ...interface{}) {
|
||||
pc, file, _, ok := runtime.Caller(2)
|
||||
if !ok {
|
||||
log.Printf(format, args...)
|
||||
return
|
||||
}
|
||||
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
log.Printf(format, args...)
|
||||
return
|
||||
}
|
||||
|
||||
funcName := filepath.Base(fn.Name())
|
||||
fileName := filepath.Base(file)
|
||||
|
||||
prefix := fmt.Sprintf("%s:%s", fileName, funcName)
|
||||
message := fmt.Sprintf(format, args...)
|
||||
log.Printf("%s %s", prefix, message)
|
||||
}
|
||||
|
||||
// Printf logs a message with caller information
|
||||
func Printf(format string, args ...interface{}) {
|
||||
logf(format, args...)
|
||||
}
|
||||
|
||||
// Debugf logs a debug message with caller information if debug is true
|
||||
func Debugf(debug bool, format string, args ...interface{}) {
|
||||
if debug {
|
||||
logf(format, args...)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user