-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield.go
394 lines (329 loc) · 10.3 KB
/
field.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package errors
import (
"context"
"fmt"
"math"
"time"
)
var (
minTimeInt64 = time.Unix(0, math.MinInt64)
maxTimeInt64 = time.Unix(0, math.MaxInt64)
)
// Field is a stack-based field and used for items that we want to store in error.
type Field struct {
Key string
Type FieldType
Integer int64
Str string
Interface interface{}
}
// Format is implement the fmt.Formatter for field.
func (f Field) Format(state fmt.State, verb rune) {
switch verb {
case 'v':
if state.Flag('+') {
fmt.Fprintf(state, "{Key: %s, Type: %s, Value: %+v}", f.Key, f.Type, f.Value())
return
}
if state.Flag('#') {
fmt.Fprintf(state, "{%s: %#v}", f.Key, f.Value())
return
}
fmt.Fprintf(state, "{Key: %s, Value: %+v}", f.Key, f.Value())
case 's':
fmt.Fprintf(state, "[%s: %s]", f.Key, f.Value())
case 'q':
fmt.Fprintf(state, "%q", f.Value())
}
}
// Value of Field.
func (f Field) Value() interface{} {
switch f.Type {
case FieldTypeString:
return f.Str
case FieldTypeInt64:
return f.Integer
case FieldTypeFloat64:
return math.Float32frombits(uint32(f.Integer))
case FieldTypeBinary:
return f.Interface
case FieldTypeByteString:
return f.Interface
case FieldTypeError:
return f.Interface
case FieldTypeTimeFull:
return f.Interface.(time.Time)
case FieldTypeTime:
return time.Unix(0, f.Integer).In(f.Interface.(*time.Location))
case FieldTypeDuration:
return time.Duration(f.Integer)
case FieldTypeBool:
var b bool
if f.Integer == 1 {
b = true
}
return b
default:
return f.Interface
}
}
// String version of Field.
func (f Field) String() string {
return fmt.Sprintf("Key: %s, Type: %s, Value: %s", f.Key, f.Type, f.Value())
}
// Is compare field type.
func (f Field) Is(fieldType FieldType) bool {
return f.Type == fieldType
}
// FieldType is a Field data type.
type FieldType int
const (
// FieldTypeUnknown is used if the data type is unknown.
FieldTypeUnknown FieldType = iota
// FieldTypeReflect is used for fields that store Reflect.
FieldTypeReflect
// FieldTypeString is used for fields that store String.
FieldTypeString
// FieldTypeInt64 is used for fields that store Int/Int64.
FieldTypeInt64
// FieldTypeFloat64 is used for fields that store Float/Float64.
FieldTypeFloat64
// FieldTypeBinary is used for fields that store binary data as []byte.
FieldTypeBinary
// FieldTypeBool is used for fields that store Bool.
FieldTypeBool
// FieldTypeByteString is used for fields that store string data as []byte.
FieldTypeByteString
// FieldTypeTime is used for fields that store UnixNano time.
FieldTypeTime
// FieldTypeTimeFull is used for fields that store time.Time.
FieldTypeTimeFull
// FieldTypeDuration is used for fields that store time.Duration.
FieldTypeDuration
// FieldTypeError is used for fields that store error.
FieldTypeError
// FieldTypeContext is used for fields that store context.Context.
FieldTypeContext
)
// String version of FieldType.
func (f FieldType) String() string {
switch f {
case FieldTypeReflect:
return "Reflect"
case FieldTypeString:
return "String"
case FieldTypeInt64:
return "Int64"
case FieldTypeFloat64:
return "Float64"
case FieldTypeBinary:
return "Binary"
case FieldTypeByteString:
return "ByteString"
case FieldTypeError:
return "Error"
case FieldTypeTimeFull:
return "TimeFull"
case FieldTypeTime:
return "Time"
case FieldTypeDuration:
return "Duration"
case FieldTypeBool:
return "Bool"
case FieldTypeContext:
return "Context"
case FieldTypeUnknown:
fallthrough
default:
return "Unknown"
}
}
// Any constructs a field with the given key and value.
func Any(key string, val interface{}) Field { // nolint: cyclop
if val == nil {
return nilField(key)
}
switch value := val.(type) {
case string:
return String(key, value)
case int:
return Int(key, value)
case int64:
return Int64(key, value)
case float64:
return Float64(key, value)
case []byte:
return Binary(key, value)
case bool:
return Bool(key, value)
case time.Time:
return Time(key, value)
case time.Duration:
return Duration(key, value)
case error:
return NamedError(key, value)
case context.Context:
return NamedContext(key, value)
}
return Field{Key: key, Type: FieldTypeUnknown, Interface: val}
}
// String constructs a field with the given key and value.
func String(key string, val string) Field {
return Field{Key: key, Type: FieldTypeString, Str: val}
}
// Int constructs a field that carries an int.
func Int(key string, value int) Field {
return Int64(key, int64(value))
}
// Int64 constructs a field that carries an int64.
func Int64(key string, value int64) Field {
return Field{Key: key, Type: FieldTypeInt64, Integer: value}
}
// Binary constructs a field that carries an opaque binary blob.
//
// Binary data is serialized in an encoding-appropriate format. For example,
// zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text,
// use ByteString.
func Binary(key string, val []byte) Field {
return Field{Key: key, Type: FieldTypeBinary, Interface: val}
}
// Bool constructs a field that carries a bool.
func Bool(key string, val bool) Field {
var iVal int64
if val {
iVal = 1
}
return Field{Key: key, Type: FieldTypeBool, Integer: iVal}
}
// nilField returns a field which will marshal explicitly as nil.
func nilField(key string) Field { return Reflect(key, nil) }
// Reflect constructs a field with the given key and an arbitrary object. It uses
// an encoding-appropriate, reflection-based function to lazily serialize nearly
// any object into the logging context, but it's relatively slow and
// allocation-heavy. Outside tests, Any is always a better choice.
//
// If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect
// includes the error message in the final log output.
func Reflect(key string, val interface{}) Field {
return Field{Key: key, Type: FieldTypeReflect, Interface: val}
}
// ByteString constructs a field that carries UTF-8 encoded text as a []byte.
// To log opaque binary blobs (which aren't necessarily valid UTF-8), use
// Binary.
func ByteString(key string, val []byte) Field {
return Field{Key: key, Type: FieldTypeByteString, Interface: val}
}
// Float64 constructs a field that carries a float64. The way the
// floating-point value is represented is encoder-dependent, so marshaling is
// necessarily lazy.
func Float64(key string, val float64) Field {
return Field{Key: key, Type: FieldTypeFloat64, Integer: int64(math.Float64bits(val))}
}
// Time constructs a Field with the given key and value. The encoder
// controls how the time is serialized.
func Time(key string, val time.Time) Field {
if val.Before(minTimeInt64) || val.After(maxTimeInt64) {
return Field{Key: key, Type: FieldTypeTimeFull, Interface: val}
}
return Field{Key: key, Type: FieldTypeTime, Integer: val.UnixNano(), Interface: val.Location()}
}
// Duration constructs a field with the given key and value. The encoder
// controls how the duration is serialized.
func Duration(key string, val time.Duration) Field {
return Field{Key: key, Type: FieldTypeDuration, Integer: int64(val)}
}
// ErrorField is shorthand for the common idiom NamedError("error", err).
func ErrorField(err error) Field {
return NamedError("error", err)
}
// NamedError constructs a field that lazily stores err.Error() under the
// provided key. Errors which also implement fmt.Formatter (like those produced
// by github.com/pkg/errors) will also have their verbose representation stored
// under key+"Verbose". If passed a nil error, the field is a no-op.
//
// For the common case in which the key is simply "error", the Error function
// is shorter and less repetitive.
func NamedError(key string, err error) Field {
return Field{Key: key, Type: FieldTypeError, Interface: err}
}
// ContextField is shorthand for the common idiom NamedContext("ctx", ctx).
func ContextField(ctx context.Context) Field {
return NamedContext("ctx", ctx)
}
// NamedContext constructs a field that carries a bool.
func NamedContext(key string, ctx context.Context) Field {
return Field{Key: key, Type: FieldTypeContext, Interface: ctx}
}
// Stack constructs a field that stores a stacktrace of the current goroutine
// under provided key. Keep in mind that taking a stacktrace is eager and
// expensive (relatively speaking); this function both makes an allocation and
// takes about two microseconds.
func Stack(key string) Field {
return StackSkip(key, 1) // skip Stack
}
// StackDepth is like Stack with support of StacktraceDepth.
func StackDepth(key string, depth int) Field {
return StackSkipDepth(key, 1, StacktraceDepth(depth)) // skip Stack
}
// StackSkip constructs a field similarly to Stack, but also skips the given
// number of frames from the top of the stacktrace.
func StackSkip(key string, skip int) Field {
// Returning the stacktrace as a string costs an allocation, but saves us
// from expanding the zapcore.Field union struct to include a byte slice. Since
// taking a stacktrace is already so expensive (~10us), the extra allocation
// is okay.
return String(key, takeStacktrace(skip+1)) // skip StackSkip
}
// StackSkipDepth is like StackSkip but also support StacktraceDepth.
func StackSkipDepth(key string, skip int, depth StacktraceDepth) Field {
return String(key, TakeStacktraceDepth(skip+1, depth)) // skip StackSkip
}
// IsNilField check of field is nilField.
func IsNilField(field Field) bool {
if field.Type != FieldTypeReflect {
return false
}
return field.Interface == nil
}
// GetChainFields finds all filed from error chain.
func GetChainFields(err error) []Field {
fields := make([]Field, 0)
for {
eErr := GetError(err)
fields = append(fields, eErr.fields...)
if eErr.cause == nil {
break
}
err = eErr.cause
}
return fields
}
// FindFieldInChain finds requested filed from error chain.
func FindFieldInChain(key string, err error) Field {
for {
eErr := GetError(err)
for _, field := range eErr.fields {
if field.Key == key {
return field
}
}
if eErr.cause == nil {
break
}
err = eErr.cause
}
return nilField(key)
}
// GetFields from passed error.
func GetFields(err error) []Field {
return GetError(err).fields
}
// GetField find you field based on the key.
func GetField(err error, key string) Field {
for _, field := range GetError(err).fields {
if field.Key == key {
return field
}
}
return nilField(key)
}