-
Notifications
You must be signed in to change notification settings - Fork 3
/
standard_formatter.go
61 lines (52 loc) · 1.63 KB
/
standard_formatter.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
package logbuch
import (
"fmt"
"time"
)
const (
// StandardTimeFormat is a synonym for time.RFC3339Nano.
StandardTimeFormat = time.RFC3339Nano
)
// StandardFormatter is the default formatter.
// It prints log messages starting with the timestamp, followed by the log level and the formatted message.
type StandardFormatter struct {
timeFormat string
disableTime bool
}
// NewStandardFormatter creates a new StandardFormatter with given timestamp format.
// The timestamp can be disabled by passing an empty string.
func NewStandardFormatter(timeFormat string) *StandardFormatter {
return &StandardFormatter{timeFormat: timeFormat, disableTime: timeFormat == ""}
}
// Fmt formats the message as described for the StandardFormatter.
func (formatter *StandardFormatter) Fmt(buffer *[]byte, level int, t time.Time, msg string, params []interface{}) {
if !formatter.disableTime {
*buffer = append(*buffer, t.Format(formatter.timeFormat)+" "...)
}
switch level {
case LevelDebug:
*buffer = append(*buffer, "[DEBUG] "...)
case LevelInfo:
*buffer = append(*buffer, "[INFO ] "...)
case LevelWarning:
*buffer = append(*buffer, "[WARN ] "...)
case LevelError:
*buffer = append(*buffer, "[ERROR] "...)
}
if len(params) == 0 {
*buffer = append(*buffer, msg...)
} else {
*buffer = append(*buffer, fmt.Sprintf(msg, params...)...)
}
if len(*buffer) == 0 || (*buffer)[len(*buffer)-1] != '\n' {
*buffer = append(*buffer, '\n')
}
}
// Pnc formats the given message and panics.
func (formatter *StandardFormatter) Pnc(msg string, params []interface{}) {
if len(params) == 0 {
panic(msg)
} else {
panic(fmt.Sprintf(msg, params...))
}
}