diff --git a/logger/options.go b/logger/options.go index 8f655dc3..4bccf085 100644 --- a/logger/options.go +++ b/logger/options.go @@ -106,7 +106,9 @@ func WithAddFields(fields ...interface{}) Option { } } } - o.Fields = append(o.Fields, fields...) + if len(fields) > 0 { + o.Fields = append(o.Fields, fields...) + } } else { o.Fields = append(o.Fields, fields...) } diff --git a/logger/slog/slog.go b/logger/slog/slog.go index ad0aacb1..ce8b9d0e 100644 --- a/logger/slog/slog.go +++ b/logger/slog/slog.go @@ -142,6 +142,7 @@ func (s *slogLogger) Fields(fields ...interface{}) logger.Logger { s.mu.RUnlock() l := &slogLogger{opts: options} + logger.WithAddFields(fields...)(&l.opts) if len(options.ContextAttrFuncs) == 0 { options.ContextAttrFuncs = logger.DefaultContextAttrFuncs diff --git a/logger/slog/slog_test.go b/logger/slog/slog_test.go index 79d75f73..3604dc7f 100644 --- a/logger/slog/slog_test.go +++ b/logger/slog/slog_test.go @@ -15,7 +15,29 @@ import ( "go.unistack.org/micro/v3/metadata" ) -func TestWithDuplicate(t *testing.T) { +func TestWithFields(t *testing.T) { + ctx := context.TODO() + buf := bytes.NewBuffer(nil) + l := NewLogger(logger.WithLevel(logger.InfoLevel), logger.WithOutput(buf), + WithHandlerFunc(slog.NewTextHandler), + logger.WithDedupKeys(true), + ) + if err := l.Init(logger.WithFields("key1", "val1")); err != nil { + t.Fatal(err) + } + + l.Info(ctx, "msg1") + + l = l.Fields("key1", "val2") + + l.Info(ctx, "msg2") + + if !bytes.Contains(buf.Bytes(), []byte(`msg=msg2 key1=val1`)) { + t.Fatalf("logger error not works, buf contains: %s", buf.Bytes()) + } +} + +func TestWithDedupKeysWithAddFields(t *testing.T) { ctx := context.TODO() buf := bytes.NewBuffer(nil) l := NewLogger(logger.WithLevel(logger.InfoLevel), logger.WithOutput(buf),