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
395
396
397
398
399
400
401
402
403
|
package logr
import (
"errors"
"fmt"
"io"
"reflect"
"strconv"
"time"
)
var (
Comma = []byte{','}
Equals = []byte{'='}
Space = []byte{' '}
Newline = []byte{'\n'}
Quote = []byte{'"'}
Colon = []byte{'"'}
)
// LogCloner is implemented by `Any` types that require a clone to be provided
// to the logger because the original may mutate.
type LogCloner interface {
LogClone() interface{}
}
// LogWriter is implemented by `Any` types that provide custom formatting for
// log output. A string representation of the type should be written directly to
// the `io.Writer`.
type LogWriter interface {
LogWrite(w io.Writer) error
}
type FieldType uint8
const (
UnknownType FieldType = iota
StringType
StringerType
StructType
ErrorType
BoolType
TimestampMillisType
TimeType
DurationType
Int64Type
Int32Type
IntType
Uint64Type
Uint32Type
UintType
Float64Type
Float32Type
BinaryType
ArrayType
MapType
)
type Field struct {
Key string
Type FieldType
Integer int64
Float float64
String string
Interface interface{}
}
func quoteString(w io.Writer, s string, shouldQuote func(s string) bool) error {
b := shouldQuote(s)
if b {
if _, err := w.Write(Quote); err != nil {
return err
}
}
if _, err := w.Write([]byte(s)); err != nil {
return err
}
if b {
if _, err := w.Write(Quote); err != nil {
return err
}
}
return nil
}
// ValueString converts a known type to a string using default formatting.
// This is called lazily by a formatter.
// Formatters can provide custom formatting or types passed via `Any` can implement
// the `LogString` interface to generate output for logging.
// If the optional shouldQuote callback is provided, then it will be called for any
// string output that could potentially need to be quoted.
func (f Field) ValueString(w io.Writer, shouldQuote func(s string) bool) error {
if shouldQuote == nil {
shouldQuote = func(s string) bool { return false }
}
var err error
switch f.Type {
case StringType:
err = quoteString(w, f.String, shouldQuote)
case StringerType:
s, ok := f.Interface.(fmt.Stringer)
if ok {
err = quoteString(w, s.String(), shouldQuote)
} else if f.Interface == nil {
err = quoteString(w, "", shouldQuote)
} else {
err = fmt.Errorf("invalid fmt.Stringer for key %s", f.Key)
}
case StructType:
s, ok := f.Interface.(LogWriter)
if ok {
err = s.LogWrite(w)
break
}
// structs that do not implement LogWriter fall back to reflection via Printf.
// TODO: create custom reflection-based encoder.
_, err = fmt.Fprintf(w, "%v", f.Interface)
case ErrorType:
// TODO: create custom error encoder.
err = quoteString(w, fmt.Sprintf("%v", f.Interface), shouldQuote)
case BoolType:
var b bool
if f.Integer != 0 {
b = true
}
_, err = io.WriteString(w, strconv.FormatBool(b))
case TimestampMillisType:
ts := time.Unix(f.Integer/1000, (f.Integer%1000)*int64(time.Millisecond))
err = quoteString(w, ts.UTC().Format(TimestampMillisFormat), shouldQuote)
case TimeType:
t, ok := f.Interface.(time.Time)
if !ok {
err = errors.New("invalid time")
break
}
err = quoteString(w, t.Format(DefTimestampFormat), shouldQuote)
case DurationType:
_, err = fmt.Fprintf(w, "%s", time.Duration(f.Integer))
case Int64Type, Int32Type, IntType:
_, err = io.WriteString(w, strconv.FormatInt(f.Integer, 10))
case Uint64Type, Uint32Type, UintType:
_, err = io.WriteString(w, strconv.FormatUint(uint64(f.Integer), 10))
case Float64Type, Float32Type:
size := 64
if f.Type == Float32Type {
size = 32
}
err = quoteString(w, strconv.FormatFloat(f.Float, 'f', -1, size), shouldQuote)
case BinaryType:
b, ok := f.Interface.([]byte)
if ok {
_, err = fmt.Fprintf(w, "[%X]", b)
break
}
_, err = fmt.Fprintf(w, "[%v]", f.Interface)
case ArrayType:
a := reflect.ValueOf(f.Interface)
arr:
for i := 0; i < a.Len(); i++ {
item := a.Index(i)
switch v := item.Interface().(type) {
case LogWriter:
if err = v.LogWrite(w); err != nil {
break arr
}
case fmt.Stringer:
if err = quoteString(w, v.String(), shouldQuote); err != nil {
break arr
}
default:
s := fmt.Sprintf("%v", v)
if err = quoteString(w, s, shouldQuote); err != nil {
break arr
}
}
if _, err = w.Write(Comma); err != nil {
break arr
}
}
case MapType:
a := reflect.ValueOf(f.Interface)
iter := a.MapRange()
it:
for iter.Next() {
if _, err = io.WriteString(w, iter.Key().String()); err != nil {
break it
}
if _, err = w.Write(Equals); err != nil {
break it
}
val := iter.Value().Interface()
switch v := val.(type) {
case LogWriter:
if err = v.LogWrite(w); err != nil {
break it
}
case fmt.Stringer:
if err = quoteString(w, v.String(), shouldQuote); err != nil {
break it
}
default:
s := fmt.Sprintf("%v", v)
if err = quoteString(w, s, shouldQuote); err != nil {
break it
}
}
if _, err = w.Write(Comma); err != nil {
break it
}
}
case UnknownType:
_, err = fmt.Fprintf(w, "%v", f.Interface)
default:
err = fmt.Errorf("invalid type %d", f.Type)
}
return err
}
func nilField(key string) Field {
return String(key, "")
}
func fieldForAny(key string, val interface{}) Field {
switch v := val.(type) {
case LogCloner:
if v == nil {
return nilField(key)
}
c := v.LogClone()
return Field{Key: key, Type: StructType, Interface: c}
case *LogCloner:
if v == nil {
return nilField(key)
}
c := (*v).LogClone()
return Field{Key: key, Type: StructType, Interface: c}
case LogWriter:
if v == nil {
return nilField(key)
}
return Field{Key: key, Type: StructType, Interface: v}
case *LogWriter:
if v == nil {
return nilField(key)
}
return Field{Key: key, Type: StructType, Interface: *v}
case bool:
return Bool(key, v)
case *bool:
if v == nil {
return nilField(key)
}
return Bool(key, *v)
case float64:
return Float64(key, v)
case *float64:
if v == nil {
return nilField(key)
}
return Float64(key, *v)
case float32:
return Float32(key, v)
case *float32:
if v == nil {
return nilField(key)
}
return Float32(key, *v)
case int:
return Int(key, v)
case *int:
if v == nil {
return nilField(key)
}
return Int(key, *v)
case int64:
return Int64(key, v)
case *int64:
if v == nil {
return nilField(key)
}
return Int64(key, *v)
case int32:
return Int32(key, v)
case *int32:
if v == nil {
return nilField(key)
}
return Int32(key, *v)
case int16:
return Int32(key, int32(v))
case *int16:
if v == nil {
return nilField(key)
}
return Int32(key, int32(*v))
case int8:
return Int32(key, int32(v))
case *int8:
if v == nil {
return nilField(key)
}
return Int32(key, int32(*v))
case string:
return String(key, v)
case *string:
if v == nil {
return nilField(key)
}
return String(key, *v)
case uint:
return Uint(key, v)
case *uint:
if v == nil {
return nilField(key)
}
return Uint(key, *v)
case uint64:
return Uint64(key, v)
case *uint64:
if v == nil {
return nilField(key)
}
return Uint64(key, *v)
case uint32:
return Uint32(key, v)
case *uint32:
if v == nil {
return nilField(key)
}
return Uint32(key, *v)
case uint16:
return Uint32(key, uint32(v))
case *uint16:
if v == nil {
return nilField(key)
}
return Uint32(key, uint32(*v))
case uint8:
return Uint32(key, uint32(v))
case *uint8:
if v == nil {
return nilField(key)
}
return Uint32(key, uint32(*v))
case []byte:
if v == nil {
return nilField(key)
}
return Field{Key: key, Type: BinaryType, Interface: v}
case time.Time:
return Time(key, v)
case *time.Time:
if v == nil {
return nilField(key)
}
return Time(key, *v)
case time.Duration:
return Duration(key, v)
case *time.Duration:
if v == nil {
return nilField(key)
}
return Duration(key, *v)
case error:
return NamedErr(key, v)
case fmt.Stringer:
if v == nil {
return nilField(key)
}
return Field{Key: key, Type: StringerType, Interface: v}
case *fmt.Stringer:
if v == nil {
return nilField(key)
}
return Field{Key: key, Type: StringerType, Interface: *v}
default:
return Field{Key: key, Type: UnknownType, Interface: val}
}
}
// FieldSorter provides sorting of an array of fields by key.
type FieldSorter []Field
func (fs FieldSorter) Len() int { return len(fs) }
func (fs FieldSorter) Less(i, j int) bool { return fs[i].Key < fs[j].Key }
func (fs FieldSorter) Swap(i, j int) { fs[i], fs[j] = fs[j], fs[i] }
|