-
Notifications
You must be signed in to change notification settings - Fork 6
/
formatter_std.go
444 lines (413 loc) · 11.1 KB
/
formatter_std.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
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
package factorlog
import (
"bytes"
"fmt"
"regexp"
"github.com/mgutz/ansi"
)
const pathSeparator = '/'
// Can hold 63 flags
type fmtVerb uint64
const (
vSTRING fmtVerb = 1 << iota
vSEVERITY
vSeverity
vseverity
vSEV
vSev
vsev
vS
vs
vDate
vTime
vUnix
vUnixNano
vFullFile
vFile
vShortFile
vLine
vPid
vFullFunction
vPkgFunction
vFunction
vColor
vMessage
vSafeMessage
)
const (
// If formatter.flags is set to any of these, we need runtime.Caller
vRUNTIME_CALLER = int(vFullFile |
vFile |
vShortFile |
vLine |
vFullFunction |
vPkgFunction |
vFunction)
)
const (
fTime_Default = 0
fTime_Provided = 1 << iota
fTime_LogDate
fTime_StampMilli
fTime_StampMicro
fTime_StampNano
)
var (
formatRe = regexp.MustCompile(`%{([A-Za-z]+)(?:\s(.*?))?}`)
argsRe = regexp.MustCompile(`(?:"(.*?)")`)
verbMap = map[string]fmtVerb{
"SEVERITY": vSEVERITY,
"Severity": vSeverity,
"severity": vseverity,
"SEV": vSEV,
"Sev": vSev,
"sev": vsev,
"S": vS,
"s": vs,
"Date": vDate,
"Time": vTime,
"Unix": vUnix,
"UnixNano": vUnixNano,
"FullFile": vFullFile,
"File": vFile,
"ShortFile": vShortFile,
"Line": vLine,
"Pid": vPid,
"FullFunction": vFullFunction,
"PkgFunction": vPkgFunction,
"Function": vFunction,
"Color": vColor,
"Message": vMessage,
"SafeMessage": vSafeMessage,
}
timeMap = map[string]int{
"15:04:05": fTime_Default,
"2006/01/02": fTime_LogDate,
"15:04:05.000": fTime_StampMilli,
"15:04:05.000000": fTime_StampMicro,
"15:04:05.000000000": fTime_StampNano,
}
)
type part struct {
verb fmtVerb
value string
args []string
flags int
}
type StdFormatter struct {
// the original format
frmt string
// a slice depicting each part of the format
// we build the final []byte from this
parts []*part
// temporary buffer to help in formatting.
// initialized by newFormatter
tmp []byte
// temporary buffer used for safe messages.
stmp []byte
// flags represents all the verbs we used.
// this is useful in speeding things up like
// not calling runtime.Caller if we don't have
// a format string that requires it
flags int
}
// Available verbs:
// %{SEVERITY} - TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL, STACK, FATAL, PANIC
// %{Severity} - Trace, Debug, Info, Warn, Error, Critical, Stack, Fatal, Panic
// %{severity} - trace, debug, info, warn, error, critical, stack, fatal, panic
// %{SEV} - TRAC, DEBG, INFO, WARN, EROR, CRIT, STAK, FATL, PANC
// %{Sev} - Trac, Debg, Info, Warn, Eror, Crit, Stak, Fatl, Panc
// %{sev} - trac, debg, info, warn, eror, crit, stak, fatl, panc
// %{S} - T, D, I, W, E, C, S, F, P
// %{s} - t, d, i, w, e, c, s, f, p
// %{Date} - Shorthand for 2006-01-02
// %{Time} - Shorthand for 15:04:05
// %{Time "<fmt>"} - Specify a format (read time.Format for details).
// Optimized formats: 2006/01/02, 15:04:05.000, 15:04:05.000000, 15:04:05.000000000
// %{Unix} - Returns the number of seconds elapsed since January 1, 1970 UTC.
// %{UnixNano} - Returns the number of nanoseconds elapsed since January 1, 1970 UTC.
// %{FullFile} - Full source file path (e.g. /dev/project/file.go).
// %{File} - The source file name (e.g. file.go).
// %{ShortFile} - The short source file name (file without .go).
// %{Line} - The source line number.
// %{FullFunction} - The full source function including path. (e.g. /dev/project.(*Type).Function)
// %{PkgFunction} - The source package and function (e.g. project.(*Type).Function)
// %{Function} - The source function name (e.g. (*Type).Function)
// %{Color "<fmt>"} - Specify a color (uses https://github.com/mgutz/ansi)
// %{Color "<fmt>" "<severity>"} - Specify a color for a given severity (e.g. %{Color "red" "ERROR"})
// %{Message} - The message.
// %{SafeMessage} - Safe message. It will escape any character below ASCII 32. This helps prevent
// attacks like using 0x08 to backspace log entries.
func NewStdFormatter(frmt string) *StdFormatter {
f := &StdFormatter{
frmt: frmt,
tmp: make([]byte, 64),
stmp: make([]byte, 0, 64),
}
matches := formatRe.FindAllStringSubmatchIndex(frmt, -1)
prev := 0
for _, m := range matches {
start, end := m[0], m[1]
verb := frmt[m[2]:m[3]]
// Try to get any arguments passed
var args []string
if m[4] != -1 {
allargs := frmt[m[4]:m[5]]
pargs := argsRe.FindAllStringSubmatch(allargs, -1)
for _, arg := range pargs {
args = append(args, arg[1])
}
}
if start > prev {
f.appendString(frmt[prev:start])
}
if v, ok := verbMap[verb]; ok {
switch v {
case vColor:
if len(args) > 0 {
if args[0] == "reset" {
f.appendString(ansi.Reset)
} else {
code := ansi.ColorCode(args[0])
if len(args) == 2 {
// If we have two arguments, that means they
// specified a severity this color applies to.
// So we have to add the part.
severity := StringToSeverity(args[1])
f.parts = append(f.parts, &part{
verb: vColor,
value: code,
flags: int(severity),
})
} else {
// We only got one argument so we can just append
// the code as a string.
f.appendString(code)
}
}
}
case vTime:
f.flags |= int(v)
if len(args) > 0 {
// Some optimizations for Time
opt_part := &part{
verb: v,
}
if ftime, ok := timeMap[args[0]]; ok {
opt_part.flags = ftime
f.parts = append(f.parts, opt_part)
} else {
opt_part.flags = fTime_Provided
opt_part.args = args
f.parts = append(f.parts, opt_part)
}
} else {
f.appendDefault(v, args)
}
default:
f.appendDefault(v, args)
}
}
prev = end
}
if frmt[prev:] != "" {
f.appendString(frmt[prev:])
}
return f
}
func (f *StdFormatter) ShouldRuntimeCaller() bool {
return f.flags&(vRUNTIME_CALLER) != 0
}
func (f *StdFormatter) appendString(s string) {
if len(s) > 0 {
f.parts = append(f.parts, &part{
verb: vSTRING,
value: s,
})
}
}
func (f *StdFormatter) appendDefault(verb fmtVerb, args []string) {
f.flags |= int(verb)
f.parts = append(f.parts, &part{
verb: verb,
args: args,
})
}
func (f *StdFormatter) Format(context LogContext) []byte {
buf := &bytes.Buffer{}
for _, p := range f.parts {
switch p.verb {
case vSTRING:
buf.WriteString(p.value)
case vSEVERITY:
buf.WriteString(UcSeverityStrings[SeverityToIndex(context.Severity)])
case vSeverity:
buf.WriteString(CapSeverityStrings[SeverityToIndex(context.Severity)])
case vseverity:
buf.WriteString(LcSeverityStrings[SeverityToIndex(context.Severity)])
case vSEV:
buf.WriteString(UcShortSeverityStrings[SeverityToIndex(context.Severity)])
case vSev:
buf.WriteString(CapShortSeverityStrings[SeverityToIndex(context.Severity)])
case vsev:
buf.WriteString(LcShortSeverityStrings[SeverityToIndex(context.Severity)])
case vS:
buf.WriteString(UcShortestSeverityStrings[SeverityToIndex(context.Severity)])
case vs:
buf.WriteString(LcShortestSeverityStrings[SeverityToIndex(context.Severity)])
case vDate:
year, month, day := context.Time.Date()
NDigits(&f.tmp, 4, 0, year)
f.tmp[4] = '-'
TwoDigits(&f.tmp, 5, int(month))
f.tmp[7] = '-'
TwoDigits(&f.tmp, 8, day)
buf.Write(f.tmp[:10])
case vTime:
// Some optimization cases.
switch {
case p.flags == fTime_LogDate:
year, month, day := context.Time.Date()
NDigits(&f.tmp, 4, 0, year)
f.tmp[4] = '/'
TwoDigits(&f.tmp, 5, int(month))
f.tmp[7] = '/'
TwoDigits(&f.tmp, 8, day)
buf.Write(f.tmp[:10])
case p.flags&(fTime_StampMilli|fTime_StampMicro|fTime_StampNano) != 0:
hour, min, sec := context.Time.Clock()
TwoDigits(&f.tmp, 0, hour)
f.tmp[2] = ':'
TwoDigits(&f.tmp, 3, min)
f.tmp[5] = ':'
TwoDigits(&f.tmp, 6, sec)
f.tmp[8] = '.'
// Depending on what kind of stamp we're dealing with, we have
// to output the correct precision.
if p.flags == fTime_StampMilli {
NDigits(&f.tmp, 3, 9, context.Time.Nanosecond()/1000000)
buf.Write(f.tmp[:12])
} else if p.flags == fTime_StampMicro {
NDigits(&f.tmp, 6, 9, context.Time.Nanosecond()/1000)
buf.Write(f.tmp[:15])
} else if p.flags == fTime_StampNano {
NDigits(&f.tmp, 9, 9, context.Time.Nanosecond())
buf.Write(f.tmp[:18])
}
case p.flags == fTime_Provided:
buf.WriteString(context.Time.Format(p.args[0]))
default:
hour, min, sec := context.Time.Clock()
TwoDigits(&f.tmp, 0, hour)
f.tmp[2] = ':'
TwoDigits(&f.tmp, 3, min)
f.tmp[5] = ':'
TwoDigits(&f.tmp, 6, sec)
buf.Write(f.tmp[:8])
}
case vUnix:
n := I64toa(&f.tmp, 0, context.Time.Unix())
buf.Write(f.tmp[:n])
case vUnixNano:
n := I64toa(&f.tmp, 0, context.Time.UnixNano())
buf.Write(f.tmp[:n])
case vPid:
n := Itoa(&f.tmp, 0, context.Pid)
buf.Write(f.tmp[:n])
case vFullFile:
buf.WriteString(context.File)
case vFile, vShortFile:
file := context.File
if len(file) == 0 {
file = "???"
} else {
slash := len(file) - 1
for ; slash >= 0; slash-- {
if file[slash] == pathSeparator {
break
}
}
if slash >= 0 {
file = file[slash+1:]
}
}
if p.verb == vShortFile {
file = file[:len(file)-3]
}
buf.WriteString(file)
case vLine:
n := Itoa(&f.tmp, 0, context.Line)
buf.Write(f.tmp[:n])
case vFullFunction:
buf.WriteString(context.Function)
case vPkgFunction:
fun := context.Function
slash := len(fun) - 1
for ; slash >= 0; slash-- {
if fun[slash] == pathSeparator {
break
}
}
if slash >= 0 {
fun = fun[slash+1:]
}
buf.WriteString(fun)
case vFunction:
fun := context.Function
slash := len(fun) - 1
lastDot := -1
for ; slash >= 0; slash-- {
if fun[slash] == pathSeparator {
break
} else if fun[slash] == '.' {
lastDot = slash
}
}
fun = fun[lastDot+1:]
buf.WriteString(fun)
case vColor:
// We must have args when we get here because of
// the parser ensuring this. No need testing for it.
if Severity(p.flags) == context.Severity {
buf.WriteString(p.value)
}
case vMessage:
if context.Format != nil {
buf.WriteString(fmt.Sprintf(*context.Format, context.Args...))
} else {
buf.WriteString(fmt.Sprint(context.Args...))
}
case vSafeMessage:
message := ""
if context.Format != nil {
message = fmt.Sprintf(*context.Format, context.Args...)
} else {
message = fmt.Sprint(context.Args...)
}
f.stmp = f.stmp[:0]
l := len(message)
ca := cap(f.stmp)
if l > ca {
f.stmp = make([]byte, 0, l)
} else if ca > 8000 { // don't let memory usage get too big
f.stmp = f.stmp[0:0:l]
}
for _, c := range message {
if int(c) < 32 {
f.tmp[0] = '\\'
f.tmp[1] = 'x'
TwoDigits(&f.tmp, 2, int(c))
f.stmp = append(f.stmp, f.tmp[:4]...)
} else {
f.stmp = append(f.stmp, byte(c))
}
}
buf.Write(f.stmp)
}
}
b := buf.Bytes()
if buf.Len() > 0 && b[len(b)-1] != '\n' {
b = append(b, '\n')
}
return b
}