-
Notifications
You must be signed in to change notification settings - Fork 246
/
encoder.go
67 lines (55 loc) · 1.83 KB
/
encoder.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
package zaputil
import (
"encoding/hex"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type jsonHexEncoder struct {
zapcore.Encoder
}
// NewJSONHexEncoder creates a JSON logger based on zapcore.NewJSONEncoder
// but overwrites encoding of byte slices. Instead encoding them with base64,
// jsonHexEncoder uses hex-encoding.
// Each hex-encoded value is prefixed with 0x so that it's clear it's a hex string.
func NewJSONHexEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder {
jsonEncoder := zapcore.NewJSONEncoder(cfg)
return &jsonHexEncoder{
Encoder: jsonEncoder,
}
}
func (enc *jsonHexEncoder) AddBinary(key string, val []byte) {
enc.AddString(key, "0x"+hex.EncodeToString(val))
}
func (enc *jsonHexEncoder) Clone() zapcore.Encoder {
encoderClone := enc.Encoder.Clone()
return &jsonHexEncoder{Encoder: encoderClone}
}
// RegisterJSONHexEncoder registers a jsonHexEncoder under "json-hex" name.
// Later, this name can be used as a value for zap.Config.Encoding to enable
// jsonHexEncoder.
func RegisterJSONHexEncoder() error {
return zap.RegisterEncoder("json-hex", func(cfg zapcore.EncoderConfig) (zapcore.Encoder, error) {
return NewJSONHexEncoder(cfg), nil
})
}
type consoleHexEncoder struct {
zapcore.Encoder
}
func NewConsoleHexEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder {
consoleEncoder := zapcore.NewConsoleEncoder(cfg)
return &consoleHexEncoder{
Encoder: consoleEncoder,
}
}
func (enc *consoleHexEncoder) AddBinary(key string, val []byte) {
enc.AddString(key, "0x"+hex.EncodeToString(val))
}
func (enc *consoleHexEncoder) Clone() zapcore.Encoder {
encoderClone := enc.Encoder.Clone()
return &consoleHexEncoder{Encoder: encoderClone}
}
func RegisterConsoleHexEncoder() error {
return zap.RegisterEncoder("console-hex", func(cfg zapcore.EncoderConfig) (zapcore.Encoder, error) {
return NewConsoleHexEncoder(cfg), nil
})
}