Debian Codegraph @

debian/vendor/github.com/pingcap/log/zap_text_encoder.go

raw
1 // Copyright 2019 PingCAP, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Copyright (c) 2016 Uber Technologies, Inc.
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining a copy
17 // of this software and associated documentation files (the "Software"), to deal
18 // in the Software without restriction, including without limitation the rights
19 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 // copies of the Software, and to permit persons to whom the Software is
21 // furnished to do so, subject to the following conditions:
22 //
23 // The above copyright notice and this permission notice shall be included in
24 // all copies or substantial portions of the Software.
25 //
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 // THE SOFTWARE.
33
34 package log
35
36 import (
37 "encoding/base64"
38 "encoding/json"
39 "fmt"
40 "math"
41 "strings"
42 "sync"
43 "time"
44 "unicode/utf8"
45
46 "go.uber.org/zap/buffer"
47 "go.uber.org/zap/zapcore"
48 )
49
50 // DefaultTimeEncoder serializes time.Time to a human-readable formatted string
51 func DefaultTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
52 s := t.Format("2006/01/02 15:04:05.000 -07:00")
53 if e, ok := enc.(*textEncoder); ok {
54 for _, c := range []byte(s) {
55 e.buf.AppendByte(c)
56 }
57 return
58 }
59 enc.AppendString(s)
60 }
61
62 // ShortCallerEncoder serializes a caller in file:line format.
63 func ShortCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
64 enc.AppendString(getCallerString(caller))
65 }
66
67 func getCallerString(ec zapcore.EntryCaller) string {
68 if !ec.Defined {
69 return "<unknown>"
70 }
71
72 idx := strings.LastIndexByte(ec.File, '/')
73 buf := _pool.Get()
74 for i := idx + 1; i < len(ec.File); i++ {
75 b := ec.File[i]
76 switch {
77 case b >= 'A' && b <= 'Z':
78 buf.AppendByte(b)
79 case b >= 'a' && b <= 'z':
80 buf.AppendByte(b)
81 case b >= '0' && b <= '9':
82 buf.AppendByte(b)
83 case b == '.' || b == '-' || b == '_':
84 buf.AppendByte(b)
85 default:
86 }
87 }
88 buf.AppendByte(':')
89 buf.AppendInt(int64(ec.Line))
90 caller := buf.String()
91 buf.Free()
92 return caller
93 }
94
95 // For JSON-escaping; see textEncoder.safeAddString below.
96 const _hex = "0123456789abcdef"
97
98 var _textPool = sync.Pool{New: func() interface{} {
99 return &textEncoder{}
100 }}
101
102 var (
103 _pool = buffer.NewPool()
104 // Get retrieves a buffer from the pool, creating one if necessary.
105 Get = _pool.Get
106 )
107
108 func getTextEncoder() *textEncoder {
109 return _textPool.Get().(*textEncoder)
110 }
111
112 func putTextEncoder(enc *textEncoder) {
113 if enc.reflectBuf != nil {
114 enc.reflectBuf.Free()
115 }
116 enc.EncoderConfig = nil
117 enc.buf = nil
118 enc.spaced = false
119 enc.openNamespaces = 0
120 enc.reflectBuf = nil
121 enc.reflectEnc = nil
122 _textPool.Put(enc)
123 }
124
125 type textEncoder struct {
126 *zapcore.EncoderConfig
127 buf *buffer.Buffer
128 spaced bool // include spaces after colons and commas
129 openNamespaces int
130 disableErrorVerbose bool
131
132 // for encoding generic values by reflection
133 reflectBuf *buffer.Buffer
134 reflectEnc *json.Encoder
135 }
136
137 // NewTextEncoder creates a fast, low-allocation Text encoder. The encoder
138 // appropriately escapes all field keys and values.
139 func NewTextEncoder(cfg *Config) zapcore.Encoder {
140 cc := zapcore.EncoderConfig{
141 // Keys can be anything except the empty string.
142 TimeKey: "time",
143 LevelKey: "level",
144 NameKey: "name",
145 CallerKey: "caller",
146 MessageKey: "message",
147 StacktraceKey: "stack",
148 LineEnding: zapcore.DefaultLineEnding,
149 EncodeLevel: zapcore.CapitalLevelEncoder,
150 EncodeTime: DefaultTimeEncoder,
151 EncodeDuration: zapcore.StringDurationEncoder,
152 EncodeCaller: ShortCallerEncoder,
153 }
154 if cfg.DisableTimestamp {
155 cc.TimeKey = ""
156 }
157 return &textEncoder{
158 EncoderConfig: &cc,
159 buf: _pool.Get(),
160 spaced: false,
161 disableErrorVerbose: cfg.DisableErrorVerbose,
162 }
163 }
164
165 func (enc *textEncoder) AddArray(key string, arr zapcore.ArrayMarshaler) error {
166 enc.addKey(key)
167 return enc.AppendArray(arr)
168 }
169
170 func (enc *textEncoder) AddObject(key string, obj zapcore.ObjectMarshaler) error {
171 enc.addKey(key)
172 return enc.AppendObject(obj)
173 }
174
175 func (enc *textEncoder) AddBinary(key string, val []byte) {
176 enc.AddString(key, base64.StdEncoding.EncodeToString(val))
177 }
178
179 func (enc *textEncoder) AddByteString(key string, val []byte) {
180 enc.addKey(key)
181 enc.AppendByteString(val)
182 }
183
184 func (enc *textEncoder) AddBool(key string, val bool) {
185 enc.addKey(key)
186 enc.AppendBool(val)
187 }
188
189 func (enc *textEncoder) AddComplex128(key string, val complex128) {
190 enc.addKey(key)
191 enc.AppendComplex128(val)
192 }
193
194 func (enc *textEncoder) AddDuration(key string, val time.Duration) {
195 enc.addKey(key)
196 enc.AppendDuration(val)
197 }
198
199 func (enc *textEncoder) AddFloat64(key string, val float64) {
200 enc.addKey(key)
201 enc.AppendFloat64(val)
202 }
203
204 func (enc *textEncoder) AddInt64(key string, val int64) {
205 enc.addKey(key)
206 enc.AppendInt64(val)
207 }
208
209 func (enc *textEncoder) resetReflectBuf() {
210 if enc.reflectBuf == nil {
211 enc.reflectBuf = _pool.Get()
212 enc.reflectEnc = json.NewEncoder(enc.reflectBuf)
213 } else {
214 enc.reflectBuf.Reset()
215 }
216 }
217
218 func (enc *textEncoder) AddReflected(key string, obj interface{}) error {
219 enc.resetReflectBuf()
220 err := enc.reflectEnc.Encode(obj)
221 if err != nil {
222 return err
223 }
224 enc.reflectBuf.TrimNewline()
225 enc.addKey(key)
226 enc.AppendByteString(enc.reflectBuf.Bytes())
227 return nil
228 }
229
230 func (enc *textEncoder) OpenNamespace(key string) {
231 enc.addKey(key)
232 enc.buf.AppendByte('{')
233 enc.openNamespaces++
234 }
235
236 func (enc *textEncoder) AddString(key, val string) {
237 enc.addKey(key)
238 enc.AppendString(val)
239 }
240
241 func (enc *textEncoder) AddTime(key string, val time.Time) {
242 enc.addKey(key)
243 enc.AppendTime(val)
244 }
245
246 func (enc *textEncoder) AddUint64(key string, val uint64) {
247 enc.addKey(key)
248 enc.AppendUint64(val)
249 }
250
251 func (enc *textEncoder) AppendArray(arr zapcore.ArrayMarshaler) error {
252 enc.addElementSeparator()
253 ne := enc.cloned()
254 ne.buf.AppendByte('[')
255 err := arr.MarshalLogArray(ne)
256 ne.buf.AppendByte(']')
257 enc.AppendByteString(ne.buf.Bytes())
258 ne.buf.Free()
259 putTextEncoder(ne)
260 return err
261 }
262
263 func (enc *textEncoder) AppendObject(obj zapcore.ObjectMarshaler) error {
264 enc.addElementSeparator()
265 ne := enc.cloned()
266 ne.buf.AppendByte('{')
267 err := obj.MarshalLogObject(ne)
268 ne.buf.AppendByte('}')
269 enc.AppendByteString(ne.buf.Bytes())
270 ne.buf.Free()
271 putTextEncoder(ne)
272 return err
273 }
274
275 func (enc *textEncoder) AppendBool(val bool) {
276 enc.addElementSeparator()
277 enc.buf.AppendBool(val)
278 }
279
280 func (enc *textEncoder) AppendByteString(val []byte) {
281 enc.addElementSeparator()
282 if !enc.needDoubleQuotes(string(val)) {
283 enc.safeAddByteString(val)
284 return
285 }
286 enc.buf.AppendByte('"')
287 enc.safeAddByteString(val)
288 enc.buf.AppendByte('"')
289 }
290
291 func (enc *textEncoder) AppendComplex128(val complex128) {
292 enc.addElementSeparator()
293 // Cast to a platform-independent, fixed-size type.
294 r, i := float64(real(val)), float64(imag(val))
295 enc.buf.AppendFloat(r, 64)
296 enc.buf.AppendByte('+')
297 enc.buf.AppendFloat(i, 64)
298 enc.buf.AppendByte('i')
299 }
300
301 func (enc *textEncoder) AppendDuration(val time.Duration) {
302 cur := enc.buf.Len()
303 enc.EncodeDuration(val, enc)
304 if cur == enc.buf.Len() {
305 // User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep
306 // JSON valid.
307 enc.AppendInt64(int64(val))
308 }
309 }
310
311 func (enc *textEncoder) AppendInt64(val int64) {
312 enc.addElementSeparator()
313 enc.buf.AppendInt(val)
314 }
315
316 func (enc *textEncoder) AppendReflected(val interface{}) error {
317 enc.resetReflectBuf()
318 err := enc.reflectEnc.Encode(val)
319 if err != nil {
320 return err
321 }
322 enc.reflectBuf.TrimNewline()
323 enc.AppendByteString(enc.reflectBuf.Bytes())
324 return nil
325 }
326
327 func (enc *textEncoder) AppendString(val string) {
328 enc.addElementSeparator()
329 enc.safeAddStringWithQuote(val)
330 }
331
332 func (enc *textEncoder) AppendTime(val time.Time) {
333 cur := enc.buf.Len()
334 enc.EncodeTime(val, enc)
335 if cur == enc.buf.Len() {
336 // User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep
337 // output JSON valid.
338 enc.AppendInt64(val.UnixNano())
339 }
340 }
341
342 func (enc *textEncoder) beginQuoteFiled() {
343 if enc.buf.Len() > 0 {
344 enc.buf.AppendByte(' ')
345 }
346 enc.buf.AppendByte('[')
347 }
348
349 func (enc *textEncoder) endQuoteFiled() {
350 enc.buf.AppendByte(']')
351 }
352
353 func (enc *textEncoder) AppendUint64(val uint64) {
354 enc.addElementSeparator()
355 enc.buf.AppendUint(val)
356 }
357
358 func (enc *textEncoder) AddComplex64(k string, v complex64) { enc.AddComplex128(k, complex128(v)) }
359 func (enc *textEncoder) AddFloat32(k string, v float32) { enc.AddFloat64(k, float64(v)) }
360 func (enc *textEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) }
361 func (enc *textEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) }
362 func (enc *textEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) }
363 func (enc *textEncoder) AddInt8(k string, v int8) { enc.AddInt64(k, int64(v)) }
364 func (enc *textEncoder) AddUint(k string, v uint) { enc.AddUint64(k, uint64(v)) }
365 func (enc *textEncoder) AddUint32(k string, v uint32) { enc.AddUint64(k, uint64(v)) }
366 func (enc *textEncoder) AddUint16(k string, v uint16) { enc.AddUint64(k, uint64(v)) }
367 func (enc *textEncoder) AddUint8(k string, v uint8) { enc.AddUint64(k, uint64(v)) }
368 func (enc *textEncoder) AddUintptr(k string, v uintptr) { enc.AddUint64(k, uint64(v)) }
369 func (enc *textEncoder) AppendComplex64(v complex64) { enc.AppendComplex128(complex128(v)) }
370 func (enc *textEncoder) AppendFloat64(v float64) { enc.appendFloat(v, 64) }
371 func (enc *textEncoder) AppendFloat32(v float32) { enc.appendFloat(float64(v), 32) }
372 func (enc *textEncoder) AppendInt(v int) { enc.AppendInt64(int64(v)) }
373 func (enc *textEncoder) AppendInt32(v int32) { enc.AppendInt64(int64(v)) }
374 func (enc *textEncoder) AppendInt16(v int16) { enc.AppendInt64(int64(v)) }
375 func (enc *textEncoder) AppendInt8(v int8) { enc.AppendInt64(int64(v)) }
376 func (enc *textEncoder) AppendUint(v uint) { enc.AppendUint64(uint64(v)) }
377 func (enc *textEncoder) AppendUint32(v uint32) { enc.AppendUint64(uint64(v)) }
378 func (enc *textEncoder) AppendUint16(v uint16) { enc.AppendUint64(uint64(v)) }
379 func (enc *textEncoder) AppendUint8(v uint8) { enc.AppendUint64(uint64(v)) }
380 func (enc *textEncoder) AppendUintptr(v uintptr) { enc.AppendUint64(uint64(v)) }
381
382 func (enc *textEncoder) Clone() zapcore.Encoder {
383 clone := enc.cloned()
384 clone.buf.Write(enc.buf.Bytes())
385 return clone
386 }
387
388 func (enc *textEncoder) cloned() *textEncoder {
389 clone := getTextEncoder()
390 clone.EncoderConfig = enc.EncoderConfig
391 clone.spaced = enc.spaced
392 clone.openNamespaces = enc.openNamespaces
393 clone.disableErrorVerbose = enc.disableErrorVerbose
394 clone.buf = _pool.Get()
395 return clone
396 }
397
398 func (enc *textEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
399 final := enc.cloned()
400 if final.TimeKey != "" {
401 final.beginQuoteFiled()
402 final.AppendTime(ent.Time)
403 final.endQuoteFiled()
404 }
405
406 if final.LevelKey != "" {
407 final.beginQuoteFiled()
408 cur := final.buf.Len()
409 final.EncodeLevel(ent.Level, final)
410 if cur == final.buf.Len() {
411 // User-supplied EncodeLevel was a no-op. Fall back to strings to keep
412 // output JSON valid.
413 final.AppendString(ent.Level.String())
414 }
415 final.endQuoteFiled()
416 }
417
418 if ent.LoggerName != "" && final.NameKey != "" {
419 final.beginQuoteFiled()
420 cur := final.buf.Len()
421 nameEncoder := final.EncodeName
422
423 // if no name encoder provided, fall back to FullNameEncoder for backwards
424 // compatibility
425 if nameEncoder == nil {
426 nameEncoder = zapcore.FullNameEncoder
427 }
428
429 nameEncoder(ent.LoggerName, final)
430 if cur == final.buf.Len() {
431 // User-supplied EncodeName was a no-op. Fall back to strings to
432 // keep output JSON valid.
433 final.AppendString(ent.LoggerName)
434 }
435 final.endQuoteFiled()
436 }
437 if ent.Caller.Defined && final.CallerKey != "" {
438 final.beginQuoteFiled()
439 cur := final.buf.Len()
440 final.EncodeCaller(ent.Caller, final)
441 if cur == final.buf.Len() {
442 // User-supplied EncodeCaller was a no-op. Fall back to strings to
443 // keep output JSON valid.
444 final.AppendString(ent.Caller.String())
445 }
446 final.endQuoteFiled()
447 }
448 // add Message
449 if len(ent.Message) > 0 {
450 final.beginQuoteFiled()
451 final.AppendString(ent.Message)
452 final.endQuoteFiled()
453 }
454 if enc.buf.Len() > 0 {
455 final.buf.AppendByte(' ')
456 final.buf.Write(enc.buf.Bytes())
457 }
458 final.addFields(fields)
459 final.closeOpenNamespaces()
460 if ent.Stack != "" && final.StacktraceKey != "" {
461 final.beginQuoteFiled()
462 final.AddString(final.StacktraceKey, ent.Stack)
463 final.endQuoteFiled()
464 }
465
466 if final.LineEnding != "" {
467 final.buf.AppendString(final.LineEnding)
468 } else {
469 final.buf.AppendString(zapcore.DefaultLineEnding)
470 }
471
472 ret := final.buf
473 putTextEncoder(final)
474 return ret, nil
475 }
476
477 func (enc *textEncoder) truncate() {
478 enc.buf.Reset()
479 }
480
481 func (enc *textEncoder) closeOpenNamespaces() {
482 for i := 0; i < enc.openNamespaces; i++ {
483 enc.buf.AppendByte('}')
484 }
485 }
486
487 func (enc *textEncoder) addKey(key string) {
488 enc.addElementSeparator()
489 enc.safeAddStringWithQuote(key)
490 enc.buf.AppendByte('=')
491 }
492
493 func (enc *textEncoder) addElementSeparator() {
494 last := enc.buf.Len() - 1
495 if last < 0 {
496 return
497 }
498 switch enc.buf.Bytes()[last] {
499 case '{', '[', ':', ',', ' ', '=':
500 return
501 default:
502 enc.buf.AppendByte(',')
503 }
504 }
505
506 func (enc *textEncoder) appendFloat(val float64, bitSize int) {
507 enc.addElementSeparator()
508 switch {
509 case math.IsNaN(val):
510 enc.buf.AppendString("NaN")
511 case math.IsInf(val, 1):
512 enc.buf.AppendString("+Inf")
513 case math.IsInf(val, -1):
514 enc.buf.AppendString("-Inf")
515 default:
516 enc.buf.AppendFloat(val, bitSize)
517 }
518 }
519
520 // safeAddString JSON-escapes a string and appends it to the internal buffer.
521 // Unlike the standard library's encoder, it doesn't attempt to protect the
522 // user from browser vulnerabilities or JSONP-related problems.
523 func (enc *textEncoder) safeAddString(s string) {
524 for i := 0; i < len(s); {
525 if enc.tryAddRuneSelf(s[i]) {
526 i++
527 continue
528 }
529 r, size := utf8.DecodeRuneInString(s[i:])
530 if enc.tryAddRuneError(r, size) {
531 i++
532 continue
533 }
534 enc.buf.AppendString(s[i : i+size])
535 i += size
536 }
537 }
538
539 // safeAddStringWithQuote will automatically add quotoes.
540 func (enc *textEncoder) safeAddStringWithQuote(s string) {
541 if !enc.needDoubleQuotes(s) {
542 enc.safeAddString(s)
543 return
544 }
545 enc.buf.AppendByte('"')
546 enc.safeAddString(s)
547 enc.buf.AppendByte('"')
548 }
549
550 // safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte.
551 func (enc *textEncoder) safeAddByteString(s []byte) {
552 for i := 0; i < len(s); {
553 if enc.tryAddRuneSelf(s[i]) {
554 i++
555 continue
556 }
557 r, size := utf8.DecodeRune(s[i:])
558 if enc.tryAddRuneError(r, size) {
559 i++
560 continue
561 }
562 enc.buf.Write(s[i : i+size])
563 i += size
564 }
565 }
566
567 // See [log-fileds](https://github.com/tikv/rfcs/blob/master/text/2018-12-19-unified-log-format.md#log-fields-section).
568 func (enc *textEncoder) needDoubleQuotes(s string) bool {
569 for i := 0; i < len(s); {
570 b := s[i]
571 if b <= 0x20 {
572 return true
573 }
574 switch b {
575 case '\\', '"', '[', ']', '=':
576 return true
577 }
578 i++
579 }
580 return false
581 }
582
583 // tryAddRuneSelf appends b if it is valid UTF-8 character represented in a single byte.
584 func (enc *textEncoder) tryAddRuneSelf(b byte) bool {
585 if b >= utf8.RuneSelf {
586 return false
587 }
588 if 0x20 <= b && b != '\\' && b != '"' {
589 enc.buf.AppendByte(b)
590 return true
591 }
592 switch b {
593 case '\\', '"':
594 enc.buf.AppendByte('\\')
595 enc.buf.AppendByte(b)
596 case '\n':
597 enc.buf.AppendByte('\\')
598 enc.buf.AppendByte('n')
599 case '\r':
600 enc.buf.AppendByte('\\')
601 enc.buf.AppendByte('r')
602 case '\t':
603 enc.buf.AppendByte('\\')
604 enc.buf.AppendByte('t')
605
606 default:
607 // Encode bytes < 0x20, except for the escape sequences above.
608 enc.buf.AppendString(`\u00`)
609 enc.buf.AppendByte(_hex[b>>4])
610 enc.buf.AppendByte(_hex[b&0xF])
611 }
612 return true
613 }
614
615 func (enc *textEncoder) tryAddRuneError(r rune, size int) bool {
616 if r == utf8.RuneError && size == 1 {
617 enc.buf.AppendString(`\ufffd`)
618 return true
619 }
620 return false
621 }
622
623 func (enc *textEncoder) addFields(fields []zapcore.Field) {
624 for _, f := range fields {
625 if f.Type == zapcore.ErrorType {
626 // handle ErrorType in pingcap/log to fix "[key=?,keyVerbose=?]" problem.
627 // see more detail at https://github.com/pingcap/log/pull/5
628 enc.encodeError(f)
629 continue
630 }
631 enc.beginQuoteFiled()
632 f.AddTo(enc)
633 enc.endQuoteFiled()
634 }
635 }
636
637 func (enc *textEncoder) encodeError(f zapcore.Field) {
638 err := f.Interface.(error)
639 basic := err.Error()
640 enc.beginQuoteFiled()
641 enc.AddString(f.Key, basic)
642 enc.endQuoteFiled()
643 if enc.disableErrorVerbose {
644 return
645 }
646 if e, isFormatter := err.(fmt.Formatter); isFormatter {
647 verbose := fmt.Sprintf("%+v", e)
648 if verbose != basic {
649 // This is a rich error type, like those produced by
650 // github.com/pkg/errors.
651 enc.beginQuoteFiled()
652 enc.AddString(f.Key+"Verbose", verbose)
653 enc.endQuoteFiled()
654 }
655 }
656 }