-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtextencoder.go
More file actions
679 lines (595 loc) · 16 KB
/
textencoder.go
File metadata and controls
679 lines (595 loc) · 16 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package logf
import (
"encoding/base64"
"math"
"sync"
"time"
"unsafe"
)
// TextEncoderConfig controls how the text encoder formats log entries —
// colors, which fields to show, and how types like time, duration, and
// errors are rendered. For a friendlier builder-style API, use Text()
// instead.
type TextEncoderConfig struct {
NoColor bool
DisableFieldTime bool
DisableFieldLevel bool
DisableFieldName bool
DisableFieldMsg bool
DisableFieldCaller bool
EncodeTime TimeEncoder
EncodeDuration DurationEncoder
EncodeError ErrorEncoder
EncodeLevel LevelEncoder
EncodeCaller CallerEncoder
}
// WithDefaults returns a copy of the config with all zero-value fields
// replaced by sensible defaults (StampMilli timestamps, string durations,
// short caller format, short level names, etc.).
func (c TextEncoderConfig) WithDefaults() TextEncoderConfig {
if c.EncodeDuration == nil {
c.EncodeDuration = StringDurationEncoder
}
if c.EncodeTime == nil {
c.EncodeTime = LayoutTimeEncoder(time.StampMilli)
}
if c.EncodeError == nil {
c.EncodeError = DefaultErrorEncoder
}
if c.EncodeLevel == nil {
c.EncodeLevel = ShortTextLevelEncoder
}
if c.EncodeCaller == nil {
c.EncodeCaller = ShortCallerEncoder
}
return c
}
// NewTextEncoder creates a text Encoder from a TextEncoderConfig struct.
// For a friendlier builder-style API, use Text() instead.
func NewTextEncoder(cfg TextEncoderConfig) Encoder {
return buildTextEncoder(cfg)
}
// Text returns a new TextEncoderBuilder — the recommended way to create a
// human-readable text encoder with ANSI colors. Colors are on by default;
// use NoColor() to disable them or check the NO_COLOR environment variable
// (https://no-color.org):
//
// enc := logf.Text().Build()
// enc := logf.Text().NoColor().Build()
//
// Respect the NO_COLOR convention:
//
// b := logf.Text()
// if _, ok := os.LookupEnv("NO_COLOR"); ok {
// b = b.NoColor()
// }
func Text() *TextEncoderBuilder {
return &TextEncoderBuilder{}
}
// TextEncoderBuilder configures and builds a text Encoder using a clean
// builder-style API. Create one with Text(), chain methods to customize,
// then call Build().
type TextEncoderBuilder struct {
cfg TextEncoderConfig
}
// NoColor disables ANSI color escape sequences in the output.
// Use this when writing to files or non-TTY destinations.
func (b *TextEncoderBuilder) NoColor() *TextEncoderBuilder {
b.cfg.NoColor = true
return b
}
// DisableTime omits the timestamp from text output entirely.
func (b *TextEncoderBuilder) DisableTime() *TextEncoderBuilder {
b.cfg.DisableFieldTime = true
return b
}
// DisableLevel omits the severity level from text output entirely.
func (b *TextEncoderBuilder) DisableLevel() *TextEncoderBuilder {
b.cfg.DisableFieldLevel = true
return b
}
// DisableMsg omits the message text from text output entirely.
func (b *TextEncoderBuilder) DisableMsg() *TextEncoderBuilder {
b.cfg.DisableFieldMsg = true
return b
}
// DisableName omits the logger name from text output entirely.
func (b *TextEncoderBuilder) DisableName() *TextEncoderBuilder {
b.cfg.DisableFieldName = true
return b
}
// DisableCaller omits the caller location from text output entirely.
func (b *TextEncoderBuilder) DisableCaller() *TextEncoderBuilder {
b.cfg.DisableFieldCaller = true
return b
}
// EncodeTime sets a custom TimeEncoder for formatting timestamps (default time.StampMilli).
func (b *TextEncoderBuilder) EncodeTime(e TimeEncoder) *TextEncoderBuilder {
b.cfg.EncodeTime = e
return b
}
// EncodeDuration sets a custom DurationEncoder for formatting durations (default string representation).
func (b *TextEncoderBuilder) EncodeDuration(e DurationEncoder) *TextEncoderBuilder {
b.cfg.EncodeDuration = e
return b
}
// EncodeLevel sets a custom LevelEncoder for formatting severity levels.
func (b *TextEncoderBuilder) EncodeLevel(e LevelEncoder) *TextEncoderBuilder {
b.cfg.EncodeLevel = e
return b
}
// EncodeCaller sets a custom CallerEncoder for formatting caller locations (default short format).
func (b *TextEncoderBuilder) EncodeCaller(e CallerEncoder) *TextEncoderBuilder {
b.cfg.EncodeCaller = e
return b
}
// EncodeError sets a custom ErrorEncoder for formatting error values.
func (b *TextEncoderBuilder) EncodeError(e ErrorEncoder) *TextEncoderBuilder {
b.cfg.EncodeError = e
return b
}
// Build finalizes the configuration and returns a ready-to-use text Encoder.
func (b *TextEncoderBuilder) Build() Encoder {
return buildTextEncoder(b.cfg)
}
func buildTextEncoder(cfg TextEncoderConfig) Encoder {
cfg = cfg.WithDefaults()
// Shared JSON encoder for nested object/array/any rendering.
jsonTEF := buildJSONEncoder(JSONEncoderConfig{
EncodeTime: cfg.EncodeTime,
EncodeDuration: cfg.EncodeDuration,
EncodeError: cfg.EncodeError,
}).(TypeEncoderFactory)
enc := &textEncoder{
TextEncoderConfig: cfg,
slot: AllocEncoderSlot(),
eseq: escSeq{noColor: cfg.NoColor},
jsonTEF: jsonTEF,
}
enc.pool = &sync.Pool{New: func() any {
return &textEncoder{
TextEncoderConfig: enc.TextEncoderConfig,
slot: enc.slot,
eseq: enc.eseq,
jsonTEF: enc.jsonTEF,
}
}}
return enc
}
type textEncoder struct {
TextEncoderConfig
pool *sync.Pool
slot int
buf *Buffer
startBufLen int
eseq escSeq
jsonTEF TypeEncoderFactory
fieldSepDone bool
groupDepth int
groupPrefix string
}
func (f *textEncoder) Clone() Encoder {
return &textEncoder{
TextEncoderConfig: f.TextEncoderConfig,
slot: f.slot,
pool: f.pool,
eseq: f.eseq,
}
}
func (f *textEncoder) Encode(e Entry) (*Buffer, error) {
clone := f.pool.Get().(*textEncoder)
buf := GetBuffer()
err := clone.encode(buf, e)
clone.buf = nil
clone.groupPrefix = ""
clone.groupDepth = 0
clone.fieldSepDone = false
f.pool.Put(clone)
if err != nil {
buf.Free()
return nil, err
}
return buf, nil
}
func (f *textEncoder) encode(buf *Buffer, e Entry) error {
f.buf = buf
f.startBufLen = buf.Len()
// Time.
if !f.DisableFieldTime && !e.Time.IsZero() {
f.eseq.dim(f.buf, func() {
f.appendTime(e.Time)
})
}
// Level.
if !f.DisableFieldLevel {
f.appendSeparator()
f.appendLevel(e.Level)
}
// Logger name.
if !f.DisableFieldName && e.LoggerName != "" {
f.appendSeparator()
f.eseq.dimItalic(f.buf, func() {
f.buf.AppendString(e.LoggerName)
f.buf.AppendByte(':')
})
}
// Message — bold + level color for WRN/ERR, bold only for others.
if !f.DisableFieldMsg && e.Text != "" {
f.appendSeparator()
mc := msgColor(e.Level)
if mc == escDefault {
f.eseq.at(f.buf, escBold, func() {
f.buf.AppendString(e.Text)
})
} else {
f.eseq.at2(f.buf, escBold, mc, func() {
f.buf.AppendString(e.Text)
})
}
}
// › separator will be emitted lazily on first addKey call.
f.fieldSepDone = false
// Skip trailing groups that would produce empty output.
loggerBag := e.LoggerBag
ctxBag := e.Bag
if len(e.Fields) == 0 {
loggerBag = skipTrailingGroups(loggerBag)
if !bagHasFields(loggerBag) {
ctxBag = skipTrailingGroups(ctxBag)
}
}
// Context fields.
f.encodeBag(ctxBag)
// Logger's fields.
f.encodeBag(loggerBag)
// Entry's fields.
for i := range e.Fields {
e.Fields[i].Accept(f)
}
// Caller — at the very end, after all fields.
if !f.DisableFieldCaller && e.CallerPC != 0 {
f.appendSeparator()
f.eseq.dimItalic(f.buf, func() {
f.buf.AppendString("→ ")
f.EncodeCaller(e.CallerPC, f.TypeEncoder(f.buf))
})
}
f.buf.AppendByte('\n')
return nil
}
func (f *textEncoder) encodeBag(bag *Bag) {
if bag == nil {
return
}
if bag.group != "" {
f.encodeBag(bag.parent)
// Push group prefix for nested fields.
f.groupPrefix += bag.group + "."
f.groupDepth++
return
}
// Field node: use cache.
if data := bag.LoadCache(f.slot); data != nil {
f.buf.AppendBytes(data)
return
}
start := f.buf.Len()
f.encodeBag(bag.parent)
for _, field := range bag.fields {
field.Accept(f)
}
if f.slot != 0 {
encoded := make([]byte, f.buf.Len()-start)
copy(encoded, f.buf.Data[start:])
bag.StoreCache(f.slot, encoded)
}
}
// --- TypeEncoder ---
func (f *textEncoder) TypeEncoder(buf *Buffer) TypeEncoder {
f.buf = buf
f.startBufLen = f.buf.Len()
return f
}
func (f *textEncoder) EncodeTypeAny(v interface{}) {
f.jsonTypeEncoder().EncodeTypeAny(v)
}
func (f *textEncoder) EncodeTypeBool(v bool) {
f.eseq.at(f.buf, escGreen, func() {
f.buf.AppendBool(v)
})
}
func (f *textEncoder) EncodeTypeInt64(v int64) {
f.eseq.at(f.buf, escGreen, func() {
f.buf.AppendInt(v)
})
}
func (f *textEncoder) EncodeTypeUint64(v uint64) {
f.eseq.at(f.buf, escGreen, func() {
f.buf.AppendUint(v)
})
}
func (f *textEncoder) EncodeTypeFloat64(v float64) {
f.eseq.at(f.buf, escGreen, func() {
switch {
case math.IsNaN(v):
f.buf.AppendString("NaN")
case math.IsInf(v, 1):
f.buf.AppendString("+Inf")
case math.IsInf(v, -1):
f.buf.AppendString("-Inf")
default:
f.buf.AppendFloat64(v)
}
})
}
func (f *textEncoder) EncodeTypeDuration(v time.Duration) {
f.EncodeDuration(v, f)
}
func (f *textEncoder) EncodeTypeTime(v time.Time) {
f.EncodeTime(v, f)
}
func (f *textEncoder) EncodeTypeString(v string) {
// Quote if contains spaces or special chars.
needsQuote := false
for i := 0; i < len(v); i++ {
if v[i] <= ' ' || v[i] == '"' || v[i] == '\\' {
needsQuote = true
break
}
}
if needsQuote {
f.buf.AppendByte('"')
_ = EscapeString(f.buf, v)
f.buf.AppendByte('"')
} else {
f.buf.AppendString(v)
}
}
func (f *textEncoder) EncodeTypeStrings(v []string) {
f.buf.AppendByte('[')
for i, s := range v {
if i > 0 {
f.buf.AppendByte(',')
}
f.EncodeTypeString(s)
}
f.buf.AppendByte(']')
}
func (f *textEncoder) EncodeTypeBytes(v []byte) {
f.buf.AppendByte('"')
base64.StdEncoding.Encode(f.buf.ExtendBytes(base64.StdEncoding.EncodedLen(len(v))), v)
f.buf.AppendByte('"')
}
func (f *textEncoder) EncodeTypeInts64(v []int64) {
f.buf.AppendByte('[')
for i, n := range v {
if i > 0 {
f.buf.AppendByte(',')
}
f.buf.AppendInt(n)
}
f.buf.AppendByte(']')
}
func (f *textEncoder) EncodeTypeFloats64(v []float64) {
f.buf.AppendByte('[')
for i, n := range v {
if i > 0 {
f.buf.AppendByte(',')
}
f.EncodeTypeFloat64(n)
}
f.buf.AppendByte(']')
}
func (f *textEncoder) EncodeTypeDurations(v []time.Duration) {
f.buf.AppendByte('[')
for i, d := range v {
if i > 0 {
f.buf.AppendByte(',')
}
f.EncodeTypeDuration(d)
}
f.buf.AppendByte(']')
}
func (f *textEncoder) EncodeTypeArray(v ArrayEncoder) {
f.jsonTypeEncoder().EncodeTypeArray(v)
}
func (f *textEncoder) EncodeTypeObject(v ObjectEncoder) {
f.jsonTypeEncoder().EncodeTypeObject(v)
}
// jsonTypeEncoder returns a JSON TypeEncoder writing to f.buf.
// Used for nested objects/arrays where JSON is more readable than key=value.
func (f *textEncoder) jsonTypeEncoder() TypeEncoder {
return f.jsonTEF.TypeEncoder(f.buf)
}
func (f *textEncoder) EncodeTypeUnsafeBytes(v unsafe.Pointer) {
f.EncodeTypeString(*(*string)(v))
}
// --- FieldEncoder ---
func (f *textEncoder) addKey(k string) {
if !f.fieldSepDone {
// First field — emit › separator.
f.fieldSepDone = true
f.appendSeparator()
f.eseq.dim(f.buf, func() {
f.buf.AppendString("›")
})
}
f.appendSeparator()
f.eseq.at2(f.buf, escBrightBlue, escItalic, func() {
if f.groupPrefix != "" {
f.buf.AppendString(f.groupPrefix)
}
f.buf.AppendString(k)
})
f.eseq.dim(f.buf, func() {
f.buf.AppendByte('=')
})
}
func (f *textEncoder) EncodeFieldAny(k string, v interface{}) { f.addKey(k); f.EncodeTypeAny(v) }
func (f *textEncoder) EncodeFieldBool(k string, v bool) { f.addKey(k); f.EncodeTypeBool(v) }
func (f *textEncoder) EncodeFieldInt64(k string, v int64) { f.addKey(k); f.EncodeTypeInt64(v) }
func (f *textEncoder) EncodeFieldUint64(k string, v uint64) { f.addKey(k); f.EncodeTypeUint64(v) }
func (f *textEncoder) EncodeFieldFloat64(k string, v float64) { f.addKey(k); f.EncodeTypeFloat64(v) }
func (f *textEncoder) EncodeFieldDuration(k string, v time.Duration) {
f.addKey(k)
f.EncodeTypeDuration(v)
}
func (f *textEncoder) EncodeFieldTime(k string, v time.Time) { f.addKey(k); f.EncodeTypeTime(v) }
func (f *textEncoder) EncodeFieldString(k string, v string) { f.addKey(k); f.EncodeTypeString(v) }
func (f *textEncoder) EncodeFieldStrings(k string, v []string) { f.addKey(k); f.EncodeTypeStrings(v) }
func (f *textEncoder) EncodeFieldBytes(k string, v []byte) { f.addKey(k); f.EncodeTypeBytes(v) }
func (f *textEncoder) EncodeFieldInts64(k string, v []int64) { f.addKey(k); f.EncodeTypeInts64(v) }
func (f *textEncoder) EncodeFieldFloats64(k string, v []float64) {
f.addKey(k)
f.EncodeTypeFloats64(v)
}
func (f *textEncoder) EncodeFieldDurations(k string, v []time.Duration) {
f.addKey(k)
f.EncodeTypeDurations(v)
}
func (f *textEncoder) EncodeFieldArray(k string, v ArrayEncoder) { f.addKey(k); f.EncodeTypeArray(v) }
func (f *textEncoder) EncodeFieldObject(k string, v ObjectEncoder) {
if k == "" {
_ = v.EncodeLogfObject(f)
return
}
f.addKey(k)
f.EncodeTypeObject(v)
}
func (f *textEncoder) EncodeFieldGroup(k string, fs []Field) {
if k == "" {
for _, field := range fs {
field.Accept(f)
}
return
}
// Push group prefix, encode fields, pop.
saved := f.groupPrefix
f.groupPrefix += k + "."
for _, field := range fs {
field.Accept(f)
}
f.groupPrefix = saved
}
func (f *textEncoder) EncodeFieldError(k string, v error) {
f.EncodeError(k, v, f)
}
// --- helpers ---
func (f *textEncoder) appendSeparator() {
if f.buf.Len() == f.startBufLen {
return
}
if f.buf.Back() == '=' {
return
}
f.buf.AppendByte(' ')
}
func (f *textEncoder) appendTime(t time.Time) {
start := f.buf.Len()
f.EncodeTime(t, f)
end := f.buf.Len()
// Strip quotes if TimeEncoder added them.
if end > start && f.buf.Data[start] == '"' && f.buf.Back() == '"' {
copy(f.buf.Data[start:], f.buf.Data[start+1:end-1])
f.buf.Data = f.buf.Data[:end-2]
}
}
func (f *textEncoder) appendLevel(lvl Level) {
f.eseq.dim(f.buf, func() {
f.buf.AppendByte('[')
})
f.eseq.at2(f.buf, escBold, levelColor(lvl), func() {
f.EncodeLevel(lvl, f)
})
f.eseq.dim(f.buf, func() {
f.buf.AppendByte(']')
})
}
func levelColor(lvl Level) escCode {
switch lvl {
case LevelDebug:
return escMagenta
case LevelInfo:
return escCyan
case LevelWarn:
return escBrightYellow
case LevelError:
return escBrightRed
default:
return escBrightRed
}
}
func msgColor(lvl Level) escCode {
switch lvl {
case LevelWarn:
return escBrightYellow
case LevelError:
return escBrightRed
default:
return escDefault // bold only, terminal default color
}
}
const escDefault escCode = 0 // no color, used with bold for default text
// --- ANSI escape sequences ---
type escCode int8
const (
escBold escCode = 1
escItalic escCode = 3
escReverse escCode = 7
escGreen escCode = 32
escBlue escCode = 34
escMagenta escCode = 35
escCyan escCode = 36
escWhite escCode = 37
escBrightBlack escCode = 90
escBrightRed escCode = 91
escBrightBlue escCode = 94
escBrightCyan escCode = 96
escBrightYellow escCode = 93
escBrightWhite escCode = 97
)
type escSeq struct{ noColor bool }
// dim emits the muted auxiliary style (time, brackets, separators).
func (es escSeq) dim(buf *Buffer, fn func()) {
if es.noColor {
fn()
return
}
buf.AppendString("\x1b[0;2m")
fn()
buf.AppendString("\x1b[0m")
}
// dimItalic emits the muted auxiliary style with italic (logger name, caller).
func (es escSeq) dimItalic(buf *Buffer, fn func()) {
if es.noColor {
fn()
return
}
buf.AppendString("\x1b[0;2;3m")
fn()
buf.AppendString("\x1b[0m")
}
func (es escSeq) at(buf *Buffer, clr escCode, fn func()) {
if es.noColor {
fn()
return
}
buf.AppendString("\x1b[")
buf.AppendInt(int64(clr))
buf.AppendByte('m')
fn()
buf.AppendString("\x1b[0m")
}
func (es escSeq) at2(buf *Buffer, clr1, clr2 escCode, fn func()) {
if es.noColor {
fn()
return
}
buf.AppendString("\x1b[")
buf.AppendInt(int64(clr1))
buf.AppendByte(';')
buf.AppendInt(int64(clr2))
buf.AppendByte('m')
fn()
buf.AppendString("\x1b[0m")
}