forked from dobyte/due
/
async_text_encoder.go
71 lines (59 loc) · 1.57 KB
/
async_text_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
68
69
70
71
/**
* @Author: fuxiao
* @Email: 576101059@qq.com
* @Date: 2022/9/1 8:50 下午
* @Desc: TODO
*/
package encoder
import (
"fmt"
"strings"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
type AsyncTextEncoder struct {
zapcore.ObjectEncoder
bufferPool buffer.Pool
timeFormat string
callerFullPath bool
isTerminal bool
}
var _ zapcore.Encoder = &AsyncTextEncoder{}
func NewAsyncTextEncoder(timeFormat string, callerFullPath, isTerminal bool) zapcore.Encoder {
return &AsyncTextEncoder{
bufferPool: buffer.NewPool(),
timeFormat: timeFormat,
callerFullPath: callerFullPath,
isTerminal: isTerminal,
}
}
func (e *AsyncTextEncoder) Clone() zapcore.Encoder {
return nil
}
func (e *AsyncTextEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
line := e.bufferPool.Get()
levelText := ent.Level.CapitalString()[0:4]
if e.isTerminal {
var levelColor int
switch ent.Level {
case zapcore.DebugLevel:
levelColor = gray
case zapcore.WarnLevel:
levelColor = yellow
case zapcore.ErrorLevel, zapcore.FatalLevel, zapcore.PanicLevel:
levelColor = red
case zapcore.InfoLevel:
levelColor = blue
default:
levelColor = blue
}
line.AppendString(fmt.Sprintf("\x1b[%dm%s", levelColor, levelText))
line.AppendString(fmt.Sprintf("\x1b[0m[%s] ", ent.Time.Format(e.timeFormat)))
} else {
line.AppendString(levelText)
line.AppendString(fmt.Sprintf("[%s] ", ent.Time.Format(e.timeFormat)))
}
line.AppendString(strings.TrimSuffix(ent.Message, "\n"))
line.AppendString("\n")
return line, nil
}