Skip to content

Commit

Permalink
feat(lwlogger): add merge logger function (#1087)
Browse files Browse the repository at this point in the history
  • Loading branch information
kolbeinn authored Dec 29, 2022
1 parent 452dff8 commit 1e569be
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lwlogger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,16 @@ func NewWithWriter(level string, out io.Writer, options ...zap.Option) *zap.Logg
return zap.New(core, options...).WithOptions(localOpts...)
}

// Merges multiple loggers into one. A call to the merged logger will be
// forwarded to all the loggers
func Merge(loggers ...*zap.Logger) *zap.Logger {
cores := make([]zapcore.Core, len(loggers))
for i, log := range loggers {
cores[i] = log.Core()
}
return zap.New(zapcore.NewTee(cores...))
}

func ValidLevel(level string) bool {
for _, l := range SupportedLogLevels {
if l == level {
Expand Down
19 changes: 19 additions & 0 deletions lwlogger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package lwlogger_test

import (
"bytes"
"io/ioutil"
"os"
"syscall"
Expand Down Expand Up @@ -219,6 +220,24 @@ func TestLoggerNewWithOptions(t *testing.T) {
assert.Contains(t, logOutput, "\"awesome\"")
}

func TestLoggerMerge(t *testing.T) {
var bufOne bytes.Buffer
var bufTwo bytes.Buffer

logOne := lwlogger.NewWithWriter("INFO", &bufOne)
logTwo := lwlogger.NewWithWriter("DEBUG", &bufTwo)

mergedLog := lwlogger.Merge(logOne, logTwo)
mergedLog.Info("ABCD")
mergedLog.Debug("XYZ")
_ = mergedLog.Sync()

assert.Contains(t, bufOne.String(), "ABCD")
assert.NotContains(t, bufOne.String(), "XYZ")
assert.Contains(t, bufTwo.String(), "ABCD")
assert.Contains(t, bufTwo.String(), "XYZ")
}

func TestValidLevel(t *testing.T) {
assert.True(t, lwlogger.ValidLevel("INFO"))
assert.True(t, lwlogger.ValidLevel("DEBUG"))
Expand Down

0 comments on commit 1e569be

Please sign in to comment.