Skip to content

Commit

Permalink
fix: Fix race condition in logger
Browse files Browse the repository at this point in the history
  • Loading branch information
rg0now committed Nov 15, 2024
1 parent 5e476c8 commit 5646b6e
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"os"
"strings"
"sync"

"github.com/pion/logging"
"golang.org/x/time/rate"
Expand Down Expand Up @@ -42,6 +43,7 @@ type LeveledLoggerFactory struct {
DefaultLogLevel logging.LogLevel
ScopeLevels map[string]logging.LogLevel
Loggers map[string]*RateLimitedLogger
lock sync.RWMutex
}

// NewLoggerFactory sets up a scoped logger for STUNner.
Expand All @@ -67,6 +69,9 @@ func (f *LeveledLoggerFactory) NewLogger(scope string) logging.LeveledLogger {

// SetLevel sets the loglevel.
func (f *LeveledLoggerFactory) SetLevel(levelSpec string) {
f.lock.Lock()
defer f.lock.Unlock()

levels := strings.Split(levelSpec, ",")
for _, s := range levels {
scopedLevel := strings.SplitN(s, ":", 2)
Expand All @@ -88,7 +93,6 @@ func (f *LeveledLoggerFactory) SetLevel(levelSpec string) {
f.DefaultLogLevel = l
continue
}

f.ScopeLevels[scope] = l
}

Expand All @@ -109,6 +113,9 @@ func (f *LeveledLoggerFactory) SetLevel(levelSpec string) {

// GetLevel gets the loglevel for the given scope.
func (f *LeveledLoggerFactory) GetLevel(scope string) string {
f.lock.RLock()
defer f.lock.RUnlock()

logLevel := f.DefaultLogLevel
scopeLevel, found := f.ScopeLevels[scope]
if found {
Expand Down Expand Up @@ -178,6 +185,9 @@ func NewRateLimitedLoggerForScope(scope string, level logging.LogLevel, writer i

// newLogger knows how to emit rate-limited loggers.
func (f *LeveledLoggerFactory) newLogger(scope string, limit rate.Limit, burst int) *RateLimitedLogger {
f.lock.Lock()
defer f.lock.Unlock()

logger, found := f.Loggers[scope]
if found {
return logger
Expand Down

0 comments on commit 5646b6e

Please sign in to comment.