From 18d43d6006940b3a8ce7f879c3f8121496b817f0 Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Mon, 22 Feb 2021 17:50:43 +0800 Subject: [PATCH] add logger wrapper (#715) * add logger wrapper --- log/log.go | 4 +++- log/log_test.go | 2 +- log/std.go | 6 +++--- log/std_test.go | 2 +- log/wrapper.go | 14 ++++++++++++++ log/wrapper_test.go | 14 ++++++++++++++ 6 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 log/wrapper.go create mode 100644 log/wrapper_test.go diff --git a/log/log.go b/log/log.go index 3884b6b54..8a89c7e6f 100644 --- a/log/log.go +++ b/log/log.go @@ -1,8 +1,10 @@ package log +import "os" + var ( // DefaultLogger is default logger. - DefaultLogger Logger = NewStdLogger() + DefaultLogger Logger = NewStdLogger(os.Stderr) ) // Logger is a logger interface. diff --git a/log/log_test.go b/log/log_test.go index d99fc121c..48cc60840 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -5,7 +5,7 @@ import ( ) func TestLogger(t *testing.T) { - logger := NewStdLogger() + logger := DefaultLogger Debug(logger).Print("log", "test debug") Info(logger).Print("log", "test info") Warn(logger).Print("log", "test warn") diff --git a/log/std.go b/log/std.go index e5eaf6ffb..6f742092b 100644 --- a/log/std.go +++ b/log/std.go @@ -3,8 +3,8 @@ package log import ( "bytes" "fmt" + "io" "log" - "os" "sync" ) @@ -16,9 +16,9 @@ type stdLogger struct { } // NewStdLogger new a std logger with options. -func NewStdLogger() Logger { +func NewStdLogger(w io.Writer) Logger { return &stdLogger{ - log: log.New(os.Stderr, "", log.LstdFlags), + log: log.New(w, "", log.LstdFlags), pool: &sync.Pool{ New: func() interface{} { return new(bytes.Buffer) diff --git a/log/std_test.go b/log/std_test.go index 60975856a..2cca13941 100644 --- a/log/std_test.go +++ b/log/std_test.go @@ -3,7 +3,7 @@ package log import "testing" func TestFmtLogger(t *testing.T) { - logger := NewStdLogger() + logger := DefaultLogger Debug(logger).Print("log", "test debug") Info(logger).Print("log", "test info") diff --git a/log/wrapper.go b/log/wrapper.go new file mode 100644 index 000000000..0330a853d --- /dev/null +++ b/log/wrapper.go @@ -0,0 +1,14 @@ +package log + +type wrapper []Logger + +func (w wrapper) Print(pairs ...interface{}) { + for _, p := range w { + p.Print(pairs...) + } +} + +// Wrap wraps multi logger. +func Wrap(l ...Logger) Logger { + return wrapper(l) +} diff --git a/log/wrapper_test.go b/log/wrapper_test.go new file mode 100644 index 000000000..e3652eb8a --- /dev/null +++ b/log/wrapper_test.go @@ -0,0 +1,14 @@ +package log + +import ( + "os" + "testing" +) + +func TestWrapper(t *testing.T) { + out := NewStdLogger(os.Stdout) + err := NewStdLogger(os.Stderr) + + l := Wrap(out, err) + l.Print("message", "test") +}