github.com/wfusion/gofusion@v1.1.14/log/context.go (about) 1 package log 2 3 import ( 4 "context" 5 6 "go.uber.org/zap" 7 8 "github.com/wfusion/gofusion/common/utils" 9 10 fusCtx "github.com/wfusion/gofusion/context" 11 ) 12 13 type Fields map[string]any 14 15 func getContextZapFields(ctx context.Context) (zapFields []zap.Field) { 16 v := ctx.Value(fusCtx.KeyLogFields) 17 if v == nil { 18 return 19 } 20 field, ok := v.(Fields) 21 if !ok { 22 return 23 } 24 return convertFieldsToZapFields(field) 25 } 26 27 func convertFieldsToZapFields(fields Fields) (zapFields []zap.Field) { 28 zapFields = make([]zap.Field, 0, len(fields)) 29 for k, v := range fields { 30 zapFields = append(zapFields, zap.Any(k, v)) 31 } 32 return 33 } 34 35 func GetCtxLogger(ctx context.Context, args ...Loggable) (logger Loggable) { 36 return utils.GetCtxAny(ctx, fusCtx.KeyLoggable, args...) 37 } 38 39 func SetCtxLogger(ctx context.Context, val Loggable) context.Context { 40 return utils.SetCtxAny(ctx, fusCtx.KeyLoggable, val) 41 } 42 43 func GetCtxFields(ctx context.Context) Fields { 44 return utils.GetCtxAny(ctx, fusCtx.KeyLogFields, (Fields)(nil)) 45 } 46 47 func SetCtxFields(ctx context.Context, fields Fields) context.Context { 48 return utils.SetCtxAny(ctx, fusCtx.KeyLogFields, fields) 49 } 50 51 func AddCtxFields(ctx context.Context, fields Fields) context.Context { 52 return SetCtxFields(ctx, utils.MapMerge(GetCtxFields(ctx), fields)) 53 } 54 55 func DelCtxFields(ctx context.Context, keys ...string) context.Context { 56 fs := GetCtxFields(ctx) 57 if len(fs) == 0 { 58 return ctx 59 } 60 keySet := utils.NewSet(keys...) 61 deleted := make(Fields, len(fs)) 62 for k, v := range fs { 63 if !keySet.Contains(k) { 64 deleted[k] = v 65 } 66 } 67 return SetCtxFields(ctx, deleted) 68 }