From ff991bf49cdcfb24457e4a6500a917deffc52a10 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Fri, 13 Dec 2024 01:04:55 +0300 Subject: [PATCH] logger/slog: fix dedup keys Signed-off-by: Vasiliy Tolstov --- logger/options.go | 4 +++- logger/slog/slog.go | 1 + logger/slog/slog_test.go | 24 +++++++++++++++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) 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), -- 2.45.2