github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/log/ctx.go (about) 1 // Copyright 2022 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package log 15 16 import ( 17 "context" 18 19 "go.uber.org/zap" 20 ) 21 22 type logCtxKeyType string 23 24 var logCtxKey = logCtxKeyType("zap-fields") 25 26 func getZapFieldsFromCtx(ctx context.Context) []zap.Field { 27 // Use a pointer to key to save one allocation. 28 fields := ctx.Value(&logCtxKey) 29 if fields == nil { 30 return nil 31 } 32 // Note that the value is a pointer to slice, to save allocation. 33 return *fields.(*[]zap.Field) 34 } 35 36 // AppendZapFieldToCtx attaches new fields to the context, which can be then 37 // used with log.WithCtx(). 38 func AppendZapFieldToCtx(ctx context.Context, newFields ...zap.Field) context.Context { 39 fields := getZapFieldsFromCtx(ctx) 40 if fields == nil { 41 // 8 fields should be enough for most situations. 42 fields = make([]zap.Field, 0, 8) 43 } 44 fields = append(fields, newFields...) 45 46 return context.WithValue(ctx, &logCtxKey, &fields) 47 }