From 3133ba42f0b59ea799de184f1a5d62c81f2c6a84 Mon Sep 17 00:00:00 2001 From: Sean Murphy Date: Sat, 15 Dec 2018 11:33:04 +0100 Subject: [PATCH] Modified logging to print line number of calling function outside logging framework --- logging.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/logging.go b/logging.go index f5e50f6..e6aa4f5 100644 --- a/logging.go +++ b/logging.go @@ -5,6 +5,8 @@ import ( "io" "log" "os" + "runtime" + "strconv" "strings" ) @@ -43,7 +45,7 @@ var ( Warning logStream Error logStream DefaultLogger logStream - LogLevel int = WARNING + LogLevel = WARNING ) func (l *logStream) Printf(format string, a ...interface{}) { @@ -53,16 +55,27 @@ func (l *logStream) Printf(format string, a ...interface{}) { } // if no specific logger is configured for this logstrea, write to stdout... + logMessage := fmt.Sprintf(format, a) + // Caller(1) is one level up the call stack - 0 identifies the caller of + // Caller which is this function... + callingStr := "[Unknown calling function]" + _, fn, lineNum, callerValid := runtime.Caller(1) + if callerValid { + callingStr = fn + ":" + strconv.Itoa(lineNum) + } + fmt.Println("Calling str = ", callingStr) + if l.s == nil { - fmt.Printf(format, a...) + fmt.Print(callingStr, " ", logMessage) return } - l.s.Printf(format, a...) + l.s.Print(callingStr, " ", logMessage) + // Printf(format, a...) } func (l *logStream) init(m io.Writer, s string, ll int) { - l.s = log.New(m, s, log.Ldate|log.Ltime|log.Lshortfile) + l.s = log.New(m, s, log.Ldate|log.Ltime) l.logLevel = ll } @@ -74,6 +87,7 @@ func determineLogLevel(lstr string) int { return logLevelStringMap[lstrLowerCase] } +// InitLogger initializes the logging system func InitLogger(logFile string, logLevelStr string, logToConsole bool) { LogLevel = determineLogLevel(logLevelStr)