make logger appliance as logger proxy (#1765)

pull/1772/head
realityone 3 years ago committed by GitHub
parent 00c05e82a3
commit 83fad75c0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 16
      log/global.go
  2. 17
      log/global_test.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.

@ -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())
}
}

Loading…
Cancel
Save