From 83fad75c0f642092619a8d4d4927f88bf200a79e Mon Sep 17 00:00:00 2001 From: realityone Date: Fri, 14 Jan 2022 13:16:25 +0800 Subject: [PATCH] make logger appliance as logger proxy (#1765) --- log/global.go | 16 +++++++++------- log/global_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/log/global.go b/log/global.go index c3dc292c2..400bf7a88 100644 --- a/log/global.go +++ b/log/global.go @@ -7,9 +7,11 @@ import ( // globalLogger is designed as a global logger in current process. var global = &loggerAppliance{} +// loggerAppliance is the proxy of `Logger` to +// make logger change will effect to all sub-logger. type loggerAppliance struct { - lock sync.Mutex - logger Logger + lock sync.Mutex + Logger helper *Helper } @@ -20,12 +22,12 @@ func init() { func (a *loggerAppliance) SetLogger(in Logger) { a.lock.Lock() defer a.lock.Unlock() - a.logger = in - a.helper = NewHelper(a.logger) + a.Logger = in + a.helper = NewHelper(a.Logger) } func (a *loggerAppliance) GetLogger() Logger { - return a.logger + return a.Logger } // SetLogger should be called before any other log call. @@ -34,9 +36,9 @@ func SetLogger(logger Logger) { global.SetLogger(logger) } -// GetLogger returns global logger in current process. +// GetLogger returns global logger appliance as logger in current process. func GetLogger() Logger { - return global.GetLogger() + return global } // Log Print log by level and keyvals. diff --git a/log/global_test.go b/log/global_test.go index 9e2d95f12..5d2f2c8f0 100644 --- a/log/global_test.go +++ b/log/global_test.go @@ -3,6 +3,7 @@ package log import ( "bytes" "fmt" + "os" "strings" "testing" ) @@ -66,3 +67,19 @@ func TestGlobalLog(t *testing.T) { t.Errorf("Expected: %s, got: %s", strings.Join(expected, "\n"), buffer.String()) } } + +func TestGlobalLogUpdate(t *testing.T) { + l := &loggerAppliance{} + l.SetLogger(NewStdLogger(os.Stdout)) + LOG := NewHelper(l) + LOG.Info("Log to stdout") + + buffer := &bytes.Buffer{} + l.SetLogger(NewStdLogger(buffer)) + LOG.Info("Log to buffer") + + expected := "INFO msg=Log to buffer\n" + if buffer.String() != expected { + t.Errorf("Expected: %s, got: %s", expected, buffer.String()) + } +}