Skip to content

Commit

Permalink
fix: fix data race in Default and SetDefault
Browse files Browse the repository at this point in the history
Fixes: #121
  • Loading branch information
op committed May 3, 2024
1 parent f9925aa commit e31f99c
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"os"
"sync"
"sync/atomic"
"time"

"github.com/muesli/termenv"
Expand All @@ -17,25 +18,27 @@ var (
registry = sync.Map{}

// defaultLogger is the default global logger instance.
defaultLogger atomic.Pointer[Logger]
defaultLoggerOnce sync.Once
defaultLogger *Logger
)

// Default returns the default logger. The default logger comes with timestamp enabled.
func Default() *Logger {
defaultLoggerOnce.Do(func() {
if defaultLogger != nil {
// already set via SetDefault.
return
}
defaultLogger = NewWithOptions(os.Stderr, Options{ReportTimestamp: true})
})
return defaultLogger
dl := defaultLogger.Load()
if dl == nil {
defaultLoggerOnce.Do(func() {
defaultLogger.CompareAndSwap(
nil, NewWithOptions(os.Stderr, Options{ReportTimestamp: true}),
)
})
dl = defaultLogger.Load()
}
return dl
}

// SetDefault sets the default global logger.
func SetDefault(logger *Logger) {
defaultLogger = logger
defaultLogger.Store(logger)
}

// New returns a new logger with the default options.
Expand Down

0 comments on commit e31f99c

Please sign in to comment.