From 3f1328de4e0601d6b00fbeb3ff9ab58d23011529 Mon Sep 17 00:00:00 2001 From: hz Date: Sun, 20 Oct 2024 01:33:20 +0800 Subject: [PATCH] more WithXXX --- slog/entry.go | 8 +++++++- slog/i.go | 4 ++++ slog/i_test.go | 2 +- slog/new_test.go | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/slog/entry.go b/slog/entry.go index cf38de8..302b014 100644 --- a/slog/entry.go +++ b/slog/entry.go @@ -975,11 +975,17 @@ func (s *Entry) leadingTags(roughSize int, lvl Level, stackFrame uintptr, msg st return } -func (s *Entry) WithContextKeys(keys ...any) *Entry { +func (s *Entry) SetContextKeys(keys ...any) *Entry { s.contextKeys = append(s.contextKeys, keys...) return s } +func (s *Entry) WithContextKeys(keys ...any) *Entry { + l := s.newChildLogger() + l.SetContextKeys(keys...) + return l +} + func (s *Entry) ctxKeysWanted() bool { return len(s.contextKeys) > 0 } func (s *Entry) ctxKeys() []any { return s.contextKeys } func (s *Entry) fromCtx(ctx context.Context) (ret Attrs) { diff --git a/slog/i.go b/slog/i.go index 154a76b..df3a6c4 100644 --- a/slog/i.go +++ b/slog/i.go @@ -76,10 +76,14 @@ type ( SetAttrs1(attrs Attrs) *Entry // Set(args ...any) *Entry // key1,val1,key2,val2,.... Of course, Attr, Attrs in args will be recognized as is + SetContextKeys(keys ...any) *Entry // given keys will be tried extracting from context.Context automatically WithContextKeys(keys ...any) *Entry // given keys will be tried extracting from context.Context automatically + SetWriter(wr io.Writer) *Entry // use the given writer WithWriter(wr io.Writer) *Entry // use the given writer AddWriter(wr io.Writer) *Entry // append more writers via this interface + SetErrorWriter(wr io.Writer) *Entry // + WithErrorWriter(wr io.Writer) *Entry // AddErrorWriter(wr io.Writer) *Entry // ResetWriters() *Entry // GetWriter() (wr LogWriter) // return level-matched writer diff --git a/slog/i_test.go b/slog/i_test.go index 1b5db33..fb73a94 100644 --- a/slog/i_test.go +++ b/slog/i_test.go @@ -484,7 +484,7 @@ func TestSlogNewWithAttrs(t *testing.T) { func TestSlogWithContext(t *testing.T) { logger := slog.New().WithAttrs(slog.String("app-version", "v0.0.1-beta")) ctx := context.WithValue(context.Background(), "ctx", "oh,oh,oh") //nolint:staticcheck - logger.WithContextKeys("ctx").InfoContext(ctx, "info msg", + logger.SetContextKeys("ctx").InfoContext(ctx, "info msg", "attr1", 111333, slog.Group("memory", slog.Int("current", 50), diff --git a/slog/new_test.go b/slog/new_test.go index f674db1..2ff1fbd 100644 --- a/slog/new_test.go +++ b/slog/new_test.go @@ -286,7 +286,7 @@ func TestWithWriter(t *testing.T) { var ss strings.Builder ss.WriteString("val") - l.WithContextKeys(&ss, "from") // set two keys here: one is a Stringer, another is a string + l.SetContextKeys(&ss, "from") // set two keys here: one is a Stringer, another is a string ctx := context.WithValue( context.WithValue(context.Background(), "from", "consul-center"),