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

fix: zap log print out multiple msg #3171

Merged
merged 3 commits into from
Feb 2, 2024
Merged
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
36 changes: 28 additions & 8 deletions contrib/log/zap/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,56 @@ import (
var _ log.Logger = (*Logger)(nil)

type Logger struct {
log *zap.Logger
log *zap.Logger
msgKey string
}

type Option func(*Logger)

// WithMessageKey with message key.
func WithMessageKey(key string) Option {
return func(l *Logger) {
l.msgKey = key
}
}

func NewLogger(zlog *zap.Logger) *Logger {
return &Logger{zlog}
return &Logger{
log: zlog,
msgKey: log.DefaultMessageKey,
}
}

func (l *Logger) Log(level log.Level, keyvals ...interface{}) error {
keylen := len(keyvals)
var (
msg = ""
keylen = len(keyvals)
)
if keylen == 0 || keylen%2 != 0 {
l.log.Warn(fmt.Sprint("Keyvalues must appear in pairs: ", keyvals))
return nil
}

data := make([]zap.Field, 0, (keylen/2)+1)
for i := 0; i < keylen; i += 2 {
if keyvals[i].(string) == l.msgKey {
msg, _ = keyvals[i+1].(string)
continue
}
data = append(data, zap.Any(fmt.Sprint(keyvals[i]), keyvals[i+1]))
}

switch level {
case log.LevelDebug:
l.log.Debug("", data...)
l.log.Debug(msg, data...)
case log.LevelInfo:
l.log.Info("", data...)
l.log.Info(msg, data...)
case log.LevelWarn:
l.log.Warn("", data...)
l.log.Warn(msg, data...)
case log.LevelError:
l.log.Error("", data...)
l.log.Error(msg, data...)
case log.LevelFatal:
l.log.Fatal("", data...)
l.log.Fatal(msg, data...)
}
return nil
}
Expand Down
2 changes: 2 additions & 0 deletions contrib/log/zap/zap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ func TestLogger(t *testing.T) {
zlog.Warnw("log", "warn")
zlog.Errorw("log", "error")
zlog.Errorw("log", "error", "except warn")
zlog.Info("hello world")

except := []string{
"{\"level\":\"debug\",\"msg\":\"\",\"log\":\"debug\"}\n",
"{\"level\":\"info\",\"msg\":\"\",\"log\":\"info\"}\n",
"{\"level\":\"warn\",\"msg\":\"\",\"log\":\"warn\"}\n",
"{\"level\":\"error\",\"msg\":\"\",\"log\":\"error\"}\n",
"{\"level\":\"warn\",\"msg\":\"Keyvalues must appear in pairs: [log error except warn]\"}\n",
"{\"level\":\"info\",\"msg\":\"hello world\"}\n", // not {"level":"info","msg":"","msg":"hello world"}
}
for i, s := range except {
if s != syncer.output[i] {
Expand Down
Loading