Add a logger that auto-includes file+callsite

This commit is contained in:
Pim van Pelt
2025-06-09 18:06:59 +02:00
parent 6371e8eee2
commit 29d0417452
3 changed files with 57 additions and 24 deletions

42
logger/logger.go Normal file
View 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...)
}
}