-
Notifications
You must be signed in to change notification settings - Fork 26
/
formatter_text.go
214 lines (190 loc) · 5.38 KB
/
formatter_text.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
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
package slog
import (
"github.com/gookit/color"
"github.com/valyala/bytebufferpool"
)
// there are built in text log template
const (
DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"
NamedTemplate = "{{datetime}} channel={{channel}} level={{level}} [file={{caller}}] message={{message}} data={{data}}\n"
)
// ColorTheme for format log to console
var ColorTheme = map[Level]color.Color{
PanicLevel: color.FgRed,
FatalLevel: color.FgRed,
ErrorLevel: color.FgMagenta,
WarnLevel: color.FgYellow,
NoticeLevel: color.OpBold,
InfoLevel: color.FgGreen,
DebugLevel: color.FgCyan,
// TraceLevel: color.FgLightGreen,
}
// TextFormatter definition
type TextFormatter struct {
// template text template for render output log messages
template string
// fields list, parsed from template string.
// NOTICE: fields contains no-field items.
// eg: ["level", "}}"}
fields []string
// TimeFormat the time format layout. default is DefaultTimeFormat
TimeFormat string
// Enable color on print log to terminal
EnableColor bool
// ColorTheme setting on render color on terminal
ColorTheme map[Level]color.Color
// FullDisplay Whether to display when record.Data, record.Extra, etc. are empty
FullDisplay bool
// EncodeFunc data encode for Record.Data, Record.Extra, etc.
//
// Default is encode by EncodeToString()
EncodeFunc func(v any) string
// CallerFormatFunc the caller format layout. default is defined by CallerFlag
CallerFormatFunc CallerFormatFn
// TODO BeforeFunc call it before format, update fields or other
// BeforeFunc func(r *Record)
}
// TextFormatterFn definition
type TextFormatterFn func(*TextFormatter)
// NewTextFormatter create new TextFormatter
func NewTextFormatter(template ...string) *TextFormatter {
var fmtTpl string
if len(template) > 0 {
fmtTpl = template[0]
} else {
fmtTpl = DefaultTemplate
}
f := &TextFormatter{
// default options
ColorTheme: ColorTheme,
TimeFormat: DefaultTimeFormat,
// EnableColor: color.SupportColor(),
// EncodeFunc: func(v any) string {
// return fmt.Sprint(v)
// },
EncodeFunc: EncodeToString,
}
f.SetTemplate(fmtTpl)
return f
}
// TextFormatterWith create new TextFormatter with options
func TextFormatterWith(fns ...TextFormatterFn) *TextFormatter {
return NewTextFormatter().WithOptions(fns...)
}
// Configure the formatter
func (f *TextFormatter) Configure(fn TextFormatterFn) *TextFormatter {
return f.WithOptions(fn)
}
// WithOptions func on the formatter
func (f *TextFormatter) WithOptions(fns ...TextFormatterFn) *TextFormatter {
for _, fn := range fns {
fn(f)
}
return f
}
// SetTemplate set the log format template and update field-map
func (f *TextFormatter) SetTemplate(fmtTpl string) {
f.template = fmtTpl
f.fields = parseTemplateToFields(fmtTpl)
}
// Template get
func (f *TextFormatter) Template() string {
return f.template
}
// WithEnableColor enable color on print log to terminal
func (f *TextFormatter) WithEnableColor(enable bool) *TextFormatter {
f.EnableColor = enable
return f
}
// Fields get export field list
func (f *TextFormatter) Fields() []string {
ss := make([]string, 0, len(f.fields)/2)
for _, s := range f.fields {
if s[0] >= 'a' && s[0] <= 'z' {
ss = append(ss, s)
}
}
return ss
}
var textPool bytebufferpool.Pool
// Format a log record
//
//goland:noinspection GoUnhandledErrorResult
func (f *TextFormatter) Format(r *Record) ([]byte, error) {
f.beforeFormat()
buf := textPool.Get()
defer textPool.Put(buf)
for _, field := range f.fields {
// is not field name. eg: "}}] "
if field[0] < 'a' || field[0] > 'z' {
// remove left "}}"
if len(field) > 1 && field[0:2] == "}}" {
buf.WriteString(field[2:])
} else {
buf.WriteString(field)
}
continue
}
switch {
case field == FieldKeyDatetime:
buf.B = r.Time.AppendFormat(buf.B, f.TimeFormat)
case field == FieldKeyTimestamp:
buf.WriteString(r.timestamp())
case field == FieldKeyCaller && r.Caller != nil:
var callerLog string
if f.CallerFormatFunc != nil {
callerLog = f.CallerFormatFunc(r.Caller)
} else {
callerLog = formatCaller(r.Caller, r.CallerFlag)
}
buf.WriteString(callerLog)
case field == FieldKeyLevel:
// output colored logs for console
if f.EnableColor {
buf.WriteString(f.renderColorByLevel(r.LevelName(), r.Level))
} else {
buf.WriteString(r.LevelName())
}
case field == FieldKeyChannel:
buf.WriteString(r.Channel)
case field == FieldKeyMessage:
// output colored logs for console
if f.EnableColor {
buf.WriteString(f.renderColorByLevel(r.Message, r.Level))
} else {
buf.WriteString(r.Message)
}
case field == FieldKeyData:
if f.FullDisplay || len(r.Data) > 0 {
buf.WriteString(f.EncodeFunc(r.Data))
}
case field == FieldKeyExtra:
if f.FullDisplay || len(r.Extra) > 0 {
buf.WriteString(f.EncodeFunc(r.Extra))
}
default:
if _, ok := r.Fields[field]; ok {
buf.WriteString(f.EncodeFunc(r.Fields[field]))
} else {
buf.WriteString(field)
}
}
}
// return buf.Bytes(), nil
return buf.B, nil
}
func (f *TextFormatter) beforeFormat() {
// if f.BeforeFunc == nil {}
if f.EncodeFunc == nil {
f.EncodeFunc = EncodeToString
}
if f.ColorTheme == nil {
f.ColorTheme = ColorTheme
}
}
func (f *TextFormatter) renderColorByLevel(s string, l Level) string {
if theme, ok := f.ColorTheme[l]; ok {
return theme.Render(s)
}
return s
}