Skip to content

Commit

Permalink
make logger appliance as logger proxy (#1765)
Browse files Browse the repository at this point in the history
  • Loading branch information
realityone authored Jan 14, 2022
1 parent 00c05e8 commit 83fad75
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
16 changes: 9 additions & 7 deletions log/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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.
Expand All @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions log/global_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package log
import (
"bytes"
"fmt"
"os"
"strings"
"testing"
)
Expand Down Expand Up @@ -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())
}
}

0 comments on commit 83fad75

Please sign in to comment.