From ea634f5fcbd69880b1af3a53fba44bf404850ab3 Mon Sep 17 00:00:00 2001 From: Suresh Kumar Date: Thu, 10 Feb 2022 11:52:18 +0530 Subject: [PATCH] Support customer logger When martian is used as package, it needs to work along with the host's logging infrastructure. By default, it retains current logging, provides an option to change it if needed. --- log/log.go | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/log/log.go b/log/log.go index 0e9ac48aa..b61987eeb 100644 --- a/log/log.go +++ b/log/log.go @@ -34,10 +34,24 @@ const ( // Default log level is Error. var ( - level = Error - lock sync.Mutex + level = Error + lock sync.Mutex + currLogger Logger = &logger{} ) +type Logger interface { + Infof(format string, args ...interface{}) + Debugf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) +} + +// SetLogger changes the default logger. This must be called very first, +// before interacting with rest of the martian package. Changing it at +// runtime is not supported. +func SetLogger(l Logger) { + currLogger = l +} + // SetLevel sets the global log level. func SetLevel(l int) { lock.Lock() @@ -48,6 +62,22 @@ func SetLevel(l int) { // Infof logs an info message. func Infof(format string, args ...interface{}) { + currLogger.Infof(format, args...) +} + +// Debugf logs a debug message. +func Debugf(format string, args ...interface{}) { + currLogger.Debugf(format, args...) +} + +// Errorf logs an error message. +func Errorf(format string, args ...interface{}) { + currLogger.Errorf(format, args...) +} + +type logger struct{} + +func (l *logger) Infof(format string, args ...interface{}) { lock.Lock() defer lock.Unlock() @@ -63,8 +93,7 @@ func Infof(format string, args ...interface{}) { log.Println(msg) } -// Debugf logs a debug message. -func Debugf(format string, args ...interface{}) { +func (l *logger) Debugf(format string, args ...interface{}) { lock.Lock() defer lock.Unlock() @@ -80,8 +109,7 @@ func Debugf(format string, args ...interface{}) { log.Println(msg) } -// Errorf logs an error message. -func Errorf(format string, args ...interface{}) { +func (l *logger) Errorf(format string, args ...interface{}) { lock.Lock() defer lock.Unlock()