From 7eb6aae949e75478e4c70132e9533ce1a8bc22ef Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Fri, 28 Oct 2022 08:14:03 +0800 Subject: [PATCH] fix: potential slice append issue (#2560) --- core/logx/fields.go | 5 ++++- core/logx/fields_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/core/logx/fields.go b/core/logx/fields.go index 1bdba318..80d5d261 100644 --- a/core/logx/fields.go +++ b/core/logx/fields.go @@ -31,7 +31,10 @@ func AddGlobalFields(fields ...LogField) { func ContextWithFields(ctx context.Context, fields ...LogField) context.Context { if val := ctx.Value(fieldsContextKey); val != nil { if arr, ok := val.([]LogField); ok { - return context.WithValue(ctx, fieldsContextKey, append(arr, fields...)) + allFields := make([]LogField, 0, len(arr)+len(fields)) + allFields = append(allFields, arr...) + allFields = append(allFields, fields...) + return context.WithValue(ctx, fieldsContextKey, allFields) } } diff --git a/core/logx/fields_test.go b/core/logx/fields_test.go index e82ed2a6..65c87b5e 100644 --- a/core/logx/fields_test.go +++ b/core/logx/fields_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "strconv" "sync" "sync/atomic" "testing" @@ -67,6 +68,22 @@ func TestWithFieldsAppend(t *testing.T) { }, fields) } +func TestWithFieldsAppendCopy(t *testing.T) { + const count = 10 + ctx := context.Background() + for i := 0; i < count; i++ { + ctx = ContextWithFields(ctx, Field(strconv.Itoa(i), 1)) + } + + af := Field("foo", 1) + bf := Field("bar", 2) + ctxa := ContextWithFields(ctx, af) + ctxb := ContextWithFields(ctx, bf) + + assert.EqualValues(t, af, ctxa.Value(fieldsContextKey).([]LogField)[count]) + assert.EqualValues(t, bf, ctxb.Value(fieldsContextKey).([]LogField)[count]) +} + func BenchmarkAtomicValue(b *testing.B) { b.ReportAllocs()