github.com/rudderlabs/rudder-go-kit@v0.30.0/logger/field.go (about) 1 package logger 2 3 import ( 4 "time" 5 6 "go.uber.org/zap" 7 ) 8 9 type FieldType uint8 10 11 const ( 12 UnknownType FieldType = iota 13 StringType 14 IntType 15 BoolType 16 FloatType 17 TimeType 18 DurationType 19 ErrorType 20 ) 21 22 type Field struct { 23 name string 24 fieldType FieldType 25 26 unknown any 27 string string 28 int int64 29 bool bool 30 float float64 31 time time.Time 32 duration time.Duration 33 error error 34 } 35 36 func (f Field) Name() string { return f.name } 37 func (f Field) Value() any { 38 switch f.fieldType { 39 case StringType: 40 return f.string 41 case IntType: 42 return f.int 43 case BoolType: 44 return f.bool 45 case FloatType: 46 return f.float 47 case TimeType: 48 return f.time 49 case DurationType: 50 return f.duration 51 case ErrorType: 52 return f.error 53 default: 54 return f.unknown 55 } 56 } 57 58 func (f Field) toZap() zap.Field { 59 switch f.fieldType { 60 case StringType: 61 return zap.String(f.name, f.string) 62 case IntType: 63 return zap.Int64(f.name, f.int) 64 case BoolType: 65 return zap.Bool(f.name, f.bool) 66 case FloatType: 67 return zap.Float64(f.name, f.float) 68 case TimeType: 69 return zap.Time(f.name, f.time) 70 case DurationType: 71 return zap.Duration(f.name, f.duration) 72 case ErrorType: 73 return zap.Error(f.error) 74 default: 75 return zap.Any(f.name, f.unknown) 76 } 77 } 78 79 func NewField(key string, v any) Field { 80 return Field{name: key, unknown: v} 81 } 82 83 func NewStringField(key, v string) Field { 84 return Field{name: key, string: v, fieldType: StringType} 85 } 86 87 func NewIntField(key string, v int64) Field { 88 return Field{name: key, int: v, fieldType: IntType} 89 } 90 91 func NewBoolField(key string, v bool) Field { 92 return Field{name: key, bool: v, fieldType: BoolType} 93 } 94 95 func NewFloatField(key string, v float64) Field { 96 return Field{name: key, float: v, fieldType: FloatType} 97 } 98 99 func NewTimeField(key string, v time.Time) Field { 100 return Field{name: key, time: v, fieldType: TimeType} 101 } 102 103 func NewDurationField(key string, v time.Duration) Field { 104 return Field{name: key, duration: v, fieldType: DurationType} 105 } 106 107 func NewErrorField(v error) Field { 108 return Field{name: "error", error: v, fieldType: ErrorType} 109 } 110 111 // Expand is useful if you want to use the type Field with the sugared logger 112 // e.g. l.Infow("my message", logger.Expand(f1, f2, f3)...) 113 func Expand(fields ...Field) []any { 114 result := make([]any, 0, len(fields)*2) 115 for _, field := range fields { 116 result = append(result, field.name, field.Value()) 117 } 118 return result 119 } 120 121 func toZap(fields []Field) []zap.Field { 122 result := make([]zap.Field, 0, len(fields)) 123 for _, field := range fields { 124 result = append(result, field.toZap()) 125 } 126 return result 127 }