Skip to content

Commit

Permalink
fix: Return inner Logger from GetLogger for log.WithContext reuse (#3455
Browse files Browse the repository at this point in the history
)

* feat: Return inner Logger from GetLogger for log.WithContext reuse
fix: Ensure thread safety by eliminating lock copy in GetLogger

* feat: Add TestContextWithGlobalLog, WithContext from GlobalLog, print kv from context

* fix: lint

---------

Co-authored-by: guangxue.wu <guangxue.wu@yunzhanghu.com>
  • Loading branch information
guangxuewu and guangxue.wu authored Oct 31, 2024
1 parent bb85d7e commit f3c4b23
Showing 2 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions log/global.go
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ var global = &loggerAppliance{}
// loggerAppliance is the proxy of `Logger` to
// make logger change will affect all sub-logger.
type loggerAppliance struct {
lock sync.Mutex
lock sync.RWMutex
Logger
}

@@ -35,7 +35,9 @@ func SetLogger(logger Logger) {

// GetLogger returns global logger appliance as logger in current process.
func GetLogger() Logger {
return global
global.lock.RLock()
defer global.lock.RUnlock()
return global.Logger
}

// Log Print log by level and keyvals.
20 changes: 20 additions & 0 deletions log/global_test.go
Original file line number Diff line number Diff line change
@@ -117,3 +117,23 @@ func TestGlobalContext(t *testing.T) {
t.Errorf("Expected:%s, got:%s", "INFO msg=111", buffer.String())
}
}

func TestContextWithGlobalLog(t *testing.T) {
buffer := &bytes.Buffer{}

type traceKey struct{}
// set "trace-id" Valuer
newLogger := With(NewStdLogger(buffer), "trace-id", Valuer(func(ctx context.Context) interface{} {
return ctx.Value(traceKey{})
}))

SetLogger(newLogger)

// add value to ctx
ctx := context.WithValue(context.Background(), traceKey{}, "test-trace-id")

_ = WithContext(ctx, GetLogger()).Log(LevelInfo)
if buffer.String() != "INFO trace-id=test-trace-id\n" {
t.Errorf("Expected:%s, got:%s", "INFO trace-id=test-trace-id", buffer.String())
}
}

0 comments on commit f3c4b23

Please sign in to comment.