From b03e4f516928ef86c3cdaf4d0ccda2b72e2d2114 Mon Sep 17 00:00:00 2001 From: phuslu Date: Sun, 28 Apr 2024 00:31:58 +0800 Subject: [PATCH] fix slog WithAttrs --- logger_go1.21.go | 2 +- logger_test.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/logger_go1.21.go b/logger_go1.21.go index 9b7bb3ce..12f4d41f 100644 --- a/logger_go1.21.go +++ b/logger_go1.21.go @@ -49,7 +49,7 @@ func (h *slogHandler) Handle(_ context.Context, r slog.Record) error { } func (h *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { - e := NewContext(nil) + e := NewContext(h.Logger.Context) for _, attr := range attrs { e = e.Any(attr.Key, attr.Value) } diff --git a/logger_test.go b/logger_test.go index 15eaa059..80e50b7e 100644 --- a/logger_test.go +++ b/logger_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" stdLog "log" + "log/slog" "net" "os" "strings" @@ -540,6 +541,24 @@ func TestStdLogger(t *testing.T) { stdLog.Printf("hello from stdLog %s", "Printf") } +func TestSlog(t *testing.T) { + var logger *slog.Logger = (&Logger{ + Level: InfoLevel, + TimeField: "date", + TimeFormat: "2006-01-02", + Caller: 1, + }).Slog() + + sublogger := logger.With("logger", "a_test_slog").With("everything", 42) + sublogger.Info("hello from sub slog Info") + sublogger.Warn("hello from sub slog Warn") + sublogger.Error("hello from sub slog Error") + + logger.Info("hello from slog Info") + logger.Warn("hello from slog Warn") + logger.Error("hello from slog Error") +} + type errno uint func (e errno) Error() string {