Skip to content

Fix concurrent data race problem #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,17 @@

package logging

import (
"sync"
)

// defaultBackend is the backend used for all logging calls.
var defaultBackend LeveledBackend
var defaultBackendMutex sync.Mutex

func init() {
defaultBackendMutex = sync.Mutex{}
}

// Backend is the interface which a log backend need to implement to be able to
// be used as a logging backend.
Expand All @@ -23,7 +32,9 @@ func SetBackend(backends ...Backend) LeveledBackend {
backend = MultiLogger(backends...)
}

defaultBackendMutex.Lock()
defaultBackend = AddModuleLevel(backend)
defaultBackendMutex.Unlock()
return defaultBackend
}

Expand Down
6 changes: 6 additions & 0 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ type moduleLeveled struct {
backend Backend
formatter Formatter
once sync.Once
mutex sync.Mutex
}

// AddModuleLevel wraps a log backend with knobs to have different log levels
Expand All @@ -81,13 +82,15 @@ func AddModuleLevel(backend Backend) LeveledBackend {
leveled = &moduleLeveled{
levels: make(map[string]Level),
backend: backend,
mutex: sync.Mutex{},
}
}
return leveled
}

// GetLevel returns the log level for the given module.
func (l *moduleLeveled) GetLevel(module string) Level {
l.mutex.Lock()
level, exists := l.levels[module]
if exists == false {
level, exists = l.levels[""]
Expand All @@ -96,12 +99,15 @@ func (l *moduleLeveled) GetLevel(module string) Level {
level = DEBUG
}
}
l.mutex.Unlock()
return level
}

// SetLevel sets the log level for the given module.
func (l *moduleLeveled) SetLevel(level Level, module string) {
l.mutex.Lock()
l.levels[module] = level
l.mutex.Unlock()
}

// IsEnabledFor will return true if logging is enabled for the given module.
Expand Down
2 changes: 2 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ func (l *Logger) log(lvl Level, format string, args ...interface{}) {
return
}

defaultBackendMutex.Lock()
defaultBackend.Log(lvl, 2+l.ExtraCalldepth, record)
defaultBackendMutex.Unlock()
}

// Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).
Expand Down