Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/use zap logger #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions v4/logger/zap/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,10 @@ type optionsKey struct{}
func WithOptions(opts ...zap.Option) logger.Option {
return logger.SetOption(optionsKey{}, opts)
}

type loggerKey struct{}

// WithLogger pass zap.Logger to logger
func WithLogger(zapLogger *zap.Logger) logger.Option {
return logger.SetOption(loggerKey{}, zapLogger)
}
9 changes: 8 additions & 1 deletion v4/logger/zap/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,17 @@ func (l *zaplog) Init(opts ...logger.Option) error {
log = log.WithOptions(options...)
}

// Using zap.Logger instance to replace internal logger
if zapLogger, ok := l.opts.Context.Value(loggerKey{}).(*zap.Logger); ok && zapLogger != nil {
l.zap = zapLogger
}

// defer log.Sync() ??

l.cfg = zapConfig
l.zap = log
if l.zap == nil {
l.zap = log
}
l.fields = make(map[string]interface{})

return nil
Expand Down
18 changes: 18 additions & 0 deletions v4/logger/zap/zap_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package zap

import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"testing"

"go-micro.dev/v4/logger"
Expand Down Expand Up @@ -44,3 +47,18 @@ func TestSetLevel(t *testing.T) {
logger.Init(logger.WithLevel(logger.InfoLevel))
l.Logf(logger.DebugLevel, "test non-show debug: %s", "debug msg")
}

func TestZapLogger(t *testing.T) {
enc := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
w := zapcore.AddSync(os.Stdout)
core := zapcore.NewCore(enc, w, zapcore.ErrorLevel)
zapLogger := zap.New(core)
l, err := NewLogger(logger.WithLevel(logger.InfoLevel), WithLogger(zapLogger))
if err != nil {
t.Fatal(err)
}
l.Logf(logger.InfoLevel, "test non-show info: %s", "info msg")
l.Logf(logger.ErrorLevel, "test show error: %s", "error msg")
logger.Init(logger.WithLevel(logger.InfoLevel))
l.Logf(logger.InfoLevel, "test non-show info: %s", "info msg")
}