logger/slog: fix dedup keys
All checks were successful
lint / lint (pull_request) Successful in 1m32s
test / test (pull_request) Successful in 12m16s

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2024-12-13 01:04:55 +03:00
parent 5a6551b703
commit ff991bf49c
3 changed files with 27 additions and 2 deletions

View File

@ -106,7 +106,9 @@ func WithAddFields(fields ...interface{}) Option {
} }
} }
} }
if len(fields) > 0 {
o.Fields = append(o.Fields, fields...) o.Fields = append(o.Fields, fields...)
}
} else { } else {
o.Fields = append(o.Fields, fields...) o.Fields = append(o.Fields, fields...)
} }

View File

@ -142,6 +142,7 @@ func (s *slogLogger) Fields(fields ...interface{}) logger.Logger {
s.mu.RUnlock() s.mu.RUnlock()
l := &slogLogger{opts: options} l := &slogLogger{opts: options}
logger.WithAddFields(fields...)(&l.opts)
if len(options.ContextAttrFuncs) == 0 { if len(options.ContextAttrFuncs) == 0 {
options.ContextAttrFuncs = logger.DefaultContextAttrFuncs options.ContextAttrFuncs = logger.DefaultContextAttrFuncs

View File

@ -15,7 +15,29 @@ import (
"go.unistack.org/micro/v3/metadata" "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() ctx := context.TODO()
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
l := NewLogger(logger.WithLevel(logger.InfoLevel), logger.WithOutput(buf), l := NewLogger(logger.WithLevel(logger.InfoLevel), logger.WithOutput(buf),