-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
111 lines (93 loc) · 1.93 KB
/
log.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
package log
import (
"fmt"
"io"
"os"
"strings"
"time"
)
type LogLevel uint8
// Error Levels that can be used to differentiate logged messages and also
// set the verbosity of logs to display.
const (
LogDebug LogLevel = iota
LogInformational
LogWarning
LogError
)
type logger interface {
createLogPoint(log logPoint)
}
type logPoint struct {
b *strings.Builder
level LogLevel
fileLine int
file string
funcName string
msg string
fields Fields
time time.Time
}
type Config struct {
ErrorPrefix string
WarnPrefix string
InfoPrefix string
DebugPrefix string
LogLevel LogLevel
Output io.Writer
// Will print error level to StdErr
// UseStdErr is ignored if Output != os.Stdout
UseStdErr bool
logger logger
levelPadding int
}
var config *Config
func InitJSONLogger(conf *Config) {
setDefaults(conf)
config = conf
config.logger = newJsonLogger()
}
func InitSimpleLogger(conf *Config) {
setDefaults(conf)
setLevelPadding(conf)
config = conf
config.logger = newSimpleLogger()
}
func setDefaults(conf *Config) {
if conf == nil {
conf = new(Config)
}
if conf.LogLevel > LogError {
panic(fmt.Sprintf("invalid log level %d", conf.LogLevel))
}
if conf.ErrorPrefix == "" {
conf.ErrorPrefix = "ERROR"
}
if conf.WarnPrefix == "" {
conf.WarnPrefix = "WARN"
}
if conf.InfoPrefix == "" {
conf.InfoPrefix = "INFO"
}
if conf.DebugPrefix == "" {
conf.DebugPrefix = "DEBUG"
}
if conf.UseStdErr && conf.Output != os.Stdout {
conf.UseStdErr = false
}
if conf.Output == nil {
conf.Output = os.Stdout
}
}
func setLevelPadding(conf *Config) {
maxPadding := func(y int) int {
if conf.levelPadding > y {
return conf.levelPadding
}
return y
}
conf.levelPadding = maxPadding(len(conf.ErrorPrefix))
conf.levelPadding = maxPadding(len(conf.WarnPrefix))
conf.levelPadding = maxPadding(len(conf.InfoPrefix))
conf.levelPadding = maxPadding(len(conf.DebugPrefix))
}