-
Notifications
You must be signed in to change notification settings - Fork 107
/
logger.go
235 lines (195 loc) · 5.83 KB
/
logger.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
package main
import (
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"github.com/op/go-logging"
)
const grimdModuleName = "grimd"
type fileConfig struct {
name string
level logging.Level
}
type boolConfig struct {
enabled bool
level logging.Level
}
type logConfig struct {
files []fileConfig
syslog boolConfig
stderr boolConfig
}
type loggingState struct {
fileBackends []logging.Backend
stdBackends []logging.Backend
files []*os.File
config *logConfig
}
func parseLogLevel(level string) (logging.Level, error) {
errorLevel := map[int]logging.Level{
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}
l, err := strconv.Atoi(level)
if err != nil {
return logging.CRITICAL, fmt.Errorf("'%s' is not an integer", level)
}
if l < 0 || l > 2 {
return logging.CRITICAL, fmt.Errorf("'%s' is not a valid value. Valid values: 0,1,2", level)
}
return errorLevel[l], nil
}
func parseLogConfig(logConfigString string) (*logConfig, error) {
var result logConfig
fileRe := regexp.MustCompile(`file:([^@]+)@(\S+)`)
boolRe := regexp.MustCompile(`(syslog|stderr)@(\S+)`)
for _, part := range strings.Split(logConfigString, ",") {
match := fileRe.FindStringSubmatch(part)
if match != nil {
l, err := parseLogLevel(match[2])
if err != nil {
return nil, fmt.Errorf("error while parsing '%s': %s", match[0], err.Error())
}
result.files = append(result.files, fileConfig{match[1], l})
continue
}
match = boolRe.FindStringSubmatch(part)
if match != nil {
l, err := parseLogLevel(match[2])
if err != nil {
return nil, fmt.Errorf("error while parsing '%s': %s", match[0], err.Error())
}
switch match[1] {
case "syslog":
result.syslog = boolConfig{true, l}
continue
case "stderr":
result.stderr = boolConfig{true, l}
continue
}
}
return nil, fmt.Errorf("error: uknown log config fragment: '%s'", part)
}
return &result, nil
}
func createLogFile(fileName string) (*os.File, error) {
if _, err := os.Stat(fileName); os.IsNotExist(err) {
if _, err := os.Create(fileName); err != nil {
return nil, fmt.Errorf("error creating log file '%s': %s", fileName, err)
}
}
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
return nil, fmt.Errorf("error opening log file: %s", err)
}
return file, nil
}
func decorateBackend(backend logging.Backend, level logging.Level, format string, moduleName string) logging.LeveledBackend {
stringFormatter := logging.MustStringFormatter(format)
beFormatter := logging.NewBackendFormatter(backend, stringFormatter)
leveled := logging.AddModuleLevel(beFormatter)
leveled.SetLevel(level, moduleName)
return leveled
}
func createLoggerFromFile(file *os.File, level logging.Level, format string, moduleName string) logging.LeveledBackend {
writer := io.Writer(file)
backend := logging.NewLogBackend(writer, "", 0)
return decorateBackend(backend, level, format, moduleName)
}
func createFileLogger(cfg fileConfig, moduleName string) (*logging.LeveledBackend, *os.File, error) {
file, err := createLogFile(cfg.name)
if err != nil {
return nil, nil, err
}
formatString := `%{time:15:04:05.000} %{level:.4s} %{shortfile} ▶ %{id:03x} %{message}`
backend := createLoggerFromFile(file, cfg.level, formatString, moduleName)
return &backend, file, nil
}
func createSyslogBackend(cfg boolConfig, moduleName string) (*logging.LeveledBackend, error) {
backend, err := logging.NewSyslogBackend("Grimd")
if err != nil {
return nil, err
}
format := `%{time:15:04:05.000} %{level:.4s} %{shortfile} ▶ %{id:03x} %{message}`
decorated := decorateBackend(backend, cfg.level, format, moduleName)
return &decorated, nil
}
func createFileLoggers(files []fileConfig, moduleName string) ([]logging.Backend, []*os.File, error) {
var backends []logging.Backend
var openFiles []*os.File
for _, f := range files {
b, file, err := createFileLogger(f, moduleName)
if err != nil {
for _, toClose := range openFiles {
err := toClose.Close()
if err != nil {
return nil, nil, err
}
}
return nil, nil, err
}
backends = append(backends, *b)
openFiles = append(openFiles, file)
}
return backends, openFiles, nil
}
// loggerInit Initializes the logger
func loggerInit(cfg string) (loggingState, error) {
var state = loggingState{}
logConfig, err := parseLogConfig(cfg)
if err != nil {
panic(err)
}
state.config = logConfig
logger = logging.MustGetLogger(grimdModuleName)
backends, openFiles, err := createFileLoggers(logConfig.files, grimdModuleName)
if err != nil {
return loggingState{}, err
}
state.fileBackends = backends
state.files = openFiles
if logConfig.stderr.enabled {
var format = `%{color}%{time:15:04:05.000} %{level:.4s} %{shortfile} ▶ %{id:03x}%{color:reset} %{message}`
stderrLogger := createLoggerFromFile(os.Stderr, logConfig.stderr.level, format, grimdModuleName)
state.stdBackends = append(state.stdBackends, stderrLogger)
}
if logConfig.syslog.enabled {
syslogLogger, err := createSyslogBackend(logConfig.syslog, grimdModuleName)
if err != nil {
panic(err)
}
state.stdBackends = append(state.stdBackends, *syslogLogger)
}
backends = append(state.stdBackends, state.fileBackends...)
logging.SetBackend(backends...)
return state, nil
}
func (s loggingState) cleanUp() {
for _, f := range s.files {
err := f.Close()
if err != nil {
logger.Error(err)
}
}
}
func (s loggingState) reopen() error {
b, f, err := createFileLoggers(s.config.files, grimdModuleName)
if err != nil {
logger.Errorf("Failed to reinit logging: %s", err)
return err
}
s.cleanUp()
s.fileBackends = b
s.files = f
backends := append(s.stdBackends, s.fileBackends...)
logging.SetBackend(backends...)
return nil
}
var (
// Initialize to a dummy but functional logger so that tested code has something to write to
logger = logging.MustGetLogger("test")
)