Skip to content

Commit

Permalink
Support customer logger (#330)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
surki committed Mar 15, 2022
1 parent b418696 commit d6ef5c8
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()

Expand All @@ -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()

Expand All @@ -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()

Expand Down

0 comments on commit d6ef5c8

Please sign in to comment.