Skip to content

Commit f896f94

Browse files
fix(logger): fix attributes leaking
1 parent ee1aa34 commit f896f94

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

logger/ctx_attributes.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,14 @@ package logger
33
import (
44
"context"
55
"log/slog"
6+
"maps"
67
)
78

89
func CtxWithLogAttributes(ctx context.Context, attrs ...slog.Attr) context.Context {
9-
attributes, _ := ctx.Value(attributesCtxKey{}).(map[string]slog.Attr)
10-
if attributes == nil {
10+
var attributes map[string]slog.Attr
11+
if existingAttributes, _ := ctx.Value(attributesCtxKey{}).(map[string]slog.Attr); existingAttributes != nil {
12+
attributes = maps.Clone(existingAttributes)
13+
} else {
1114
attributes = make(map[string]slog.Attr)
1215
}
1316

logger/ctx_attributes_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ func TestCtxWithLogAttributes(t *testing.T) {
1414
logger := slog.New(handler)
1515
ctx := CtxWithLogger(context.Background(), logger)
1616
ctx = CtxWithLogAttributes(ctx, slog.String("toto", "tutu"), slog.Int("?", 42))
17+
ctx2 := CtxWithLogAttributes(ctx, slog.String("tata", "tonton"), slog.Int("?", 404))
1718

1819
require.Empty(t, handler.GetLogs())
1920
Debug(ctx, "test")
@@ -31,4 +32,8 @@ func TestCtxWithLogAttributes(t *testing.T) {
3132
ErrorAsWarning(ctx, errtrace.New("test"))
3233
require.Len(t, handler.GetLogs(), 5)
3334
require.Equal(t, 3, handler.GetLogs()[4].NumAttrs())
35+
36+
Debug(ctx2, "test")
37+
require.Len(t, handler.GetLogs(), 6)
38+
require.Equal(t, 3, handler.GetLogs()[5].NumAttrs())
3439
}

0 commit comments

Comments
 (0)