forked from papertrail/remote_syslog2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
421 lines (384 loc) · 11.7 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
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
// Module level logging for Go
//
// This package provides an alternative to the standard library log package.
//
// The actual logging functions never return errors. If you are logging
// something, you really don't want to be worried about the logging
// having trouble.
//
// Modules have names that are defined by dotted strings.
// e.g. "first.second.third"
//
// There is a root module that has the name "". Each module
// (except the root module) has a parent, identified by the part of
// the name without the last dotted value.
// e.g. the parent of "first.second.third" is "first.second"
// the parent of "first.second" is "first"
// the parent of "first" is "" (the root module)
//
// Each module can specify its own severity level. Logging calls that are of
// a lower severity than the module's effective severity level are not written
// out.
//
// Loggers are created using the GetLogger function.
// e.g. logger := loggo.GetLogger("foo.bar")
//
// By default there is one writer registered, which will write to Stderr,
// and the root module, which will only emit warnings and above.
// If you want to continue using the default
// logger, but have it emit all logging levels you need to do the following.
//
// writer, _, err := loggo.RemoveWriter("default")
// // err is non-nil if and only if the name isn't found.
// loggo.RegisterWriter("default", writer, loggo.TRACE)
package loggo
import (
"fmt"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
)
// Level holds a severity level.
type Level uint32
// The severity levels. Higher values are more considered more
// important.
const (
UNSPECIFIED Level = iota
TRACE
DEBUG
INFO
WARNING
ERROR
CRITICAL
)
// A Logger represents a logging module. It has an associated logging
// level which can be changed; messages of lesser severity will
// be dropped. Loggers have a hierarchical relationship - see
// the package documentation.
//
// The zero Logger value is usable - any messages logged
// to it will be sent to the root Logger.
type Logger struct {
impl *module
}
type module struct {
name string
level Level
parent *module
}
// Initially the modules map only contains the root module.
var (
root = &module{level: WARNING}
modulesMutex sync.Mutex
modules = map[string]*module{
"": root,
}
)
func (level Level) String() string {
switch level {
case UNSPECIFIED:
return "UNSPECIFIED"
case TRACE:
return "TRACE"
case DEBUG:
return "DEBUG"
case INFO:
return "INFO"
case WARNING:
return "WARNING"
case ERROR:
return "ERROR"
case CRITICAL:
return "CRITICAL"
}
return "<unknown>"
}
// get atomically gets the value of the given level.
func (level *Level) get() Level {
return Level(atomic.LoadUint32((*uint32)(level)))
}
// set atomically sets the value of the receiver
// to the given level.
func (level *Level) set(newLevel Level) {
atomic.StoreUint32((*uint32)(level), uint32(newLevel))
}
// getLoggerInternal assumes that the modulesMutex is locked.
func getLoggerInternal(name string) Logger {
impl, found := modules[name]
if found {
return Logger{impl}
}
parentName := ""
if i := strings.LastIndex(name, "."); i >= 0 {
parentName = name[0:i]
}
parent := getLoggerInternal(parentName).impl
impl = &module{name, UNSPECIFIED, parent}
modules[name] = impl
return Logger{impl}
}
// GetLogger returns a Logger for the given module name,
// creating it and its parents if necessary.
func GetLogger(name string) Logger {
// Lowercase the module name, and look for it in the modules map.
name = strings.ToLower(name)
modulesMutex.Lock()
defer modulesMutex.Unlock()
return getLoggerInternal(name)
}
// LoggerInfo returns information about the configured loggers and their logging
// levels. The information is returned in the format expected by
// ConfigureModules. Loggers with UNSPECIFIED level will not
// be included.
func LoggerInfo() string {
output := []string{}
// output in alphabetical order.
keys := []string{}
modulesMutex.Lock()
defer modulesMutex.Unlock()
for key := range modules {
keys = append(keys, key)
}
sort.Strings(keys)
for _, name := range keys {
mod := modules[name]
severity := mod.level
if severity == UNSPECIFIED {
continue
}
output = append(output, fmt.Sprintf("%s=%s", mod.Name(), severity))
}
return strings.Join(output, ";")
}
// ParseConfigurationString parses a logger configuration string into a map of
// logger names and their associated log level. This method is provided to
// allow other programs to pre-validate a configuration string rather than
// just calling ConfigureLoggers.
//
// Loggers are colon- or semicolon-separated; each module is specified as
// <modulename>=<level>. White space outside of module names and levels is
// ignored. The root module is specified with the name "<root>".
//
// An example specification:
// `<root>=ERROR; foo.bar=WARNING`
func ParseConfigurationString(specification string) (map[string]Level, error) {
values := strings.FieldsFunc(specification, func(r rune) bool { return r == ';' || r == ':' })
levels := make(map[string]Level)
for _, value := range values {
s := strings.SplitN(value, "=", 2)
if len(s) < 2 {
return nil, fmt.Errorf("logger specification expected '=', found %q", value)
}
name := strings.TrimSpace(s[0])
levelStr := strings.TrimSpace(s[1])
if name == "" || levelStr == "" {
return nil, fmt.Errorf("logger specification %q has blank name or level", value)
}
if name == "<root>" {
name = ""
}
level, ok := ParseLevel(levelStr)
if !ok {
return nil, fmt.Errorf("unknown severity level %q", levelStr)
}
levels[name] = level
}
return levels, nil
}
// ConfigureLoggers configures loggers according to the given string
// specification, which specifies a set of modules and their associated
// logging levels. Loggers are colon- or semicolon-separated; each
// module is specified as <modulename>=<level>. White space outside of
// module names and levels is ignored. The root module is specified
// with the name "<root>".
//
// An example specification:
// `<root>=ERROR; foo.bar=WARNING`
func ConfigureLoggers(specification string) error {
if specification == "" {
return nil
}
levels, err := ParseConfigurationString(specification)
if err != nil {
return err
}
for name, level := range levels {
GetLogger(name).SetLogLevel(level)
}
return nil
}
// ResetLogging iterates through the known modules and sets the levels of all
// to UNSPECIFIED, except for <root> which is set to WARNING.
func ResetLoggers() {
modulesMutex.Lock()
defer modulesMutex.Unlock()
for name, module := range modules {
if name == "" {
module.level.set(WARNING)
} else {
module.level.set(UNSPECIFIED)
}
}
}
// ParseLevel converts a string representation of a logging level to a
// Level. It returns the level and whether it was valid or not.
func ParseLevel(level string) (Level, bool) {
level = strings.ToUpper(level)
switch level {
case "UNSPECIFIED":
return UNSPECIFIED, true
case "TRACE":
return TRACE, true
case "DEBUG":
return DEBUG, true
case "INFO":
return INFO, true
case "WARN", "WARNING":
return WARNING, true
case "ERROR":
return ERROR, true
case "CRITICAL":
return CRITICAL, true
}
return UNSPECIFIED, false
}
func (logger Logger) getModule() *module {
if logger.impl == nil {
return root
}
return logger.impl
}
// Name returns the logger's module name.
func (logger Logger) Name() string {
return logger.getModule().Name()
}
// LogLevel returns the configured log level of the logger.
func (logger Logger) LogLevel() Level {
return logger.getModule().level.get()
}
func (module *module) getEffectiveLogLevel() Level {
// Note: the root module is guaranteed to have a
// specified logging level, so acts as a suitable sentinel
// for this loop.
for {
if level := module.level.get(); level != UNSPECIFIED {
return level
}
module = module.parent
}
panic("unreachable")
}
func (module *module) Name() string {
if module.name == "" {
return "<root>"
}
return module.name
}
// EffectiveLogLevel returns the effective log level of
// the receiver - that is, messages with a lesser severity
// level will be discarded.
//
// If the log level of the receiver is unspecified,
// it will be taken from the effective log level of its
// parent.
func (logger Logger) EffectiveLogLevel() Level {
return logger.getModule().getEffectiveLogLevel()
}
// SetLogLevel sets the severity level of the given logger.
// The root logger cannot be set to UNSPECIFIED level.
// See EffectiveLogLevel for how this affects the
// actual messages logged.
func (logger Logger) SetLogLevel(level Level) {
module := logger.getModule()
// The root module can't be unspecified.
if module.name == "" && level == UNSPECIFIED {
level = WARNING
}
module.level.set(level)
}
// Logf logs a printf-formatted message at the given level.
// A message will be discarded if level is less than the
// the effective log level of the logger.
// Note that the writers may also filter out messages that
// are less than their registered minimum severity level.
func (logger Logger) Logf(level Level, message string, args ...interface{}) {
if logger.getModule().getEffectiveLogLevel() > level ||
!WillWrite(level) ||
level < TRACE ||
level > CRITICAL {
return
}
// Gather time, and filename, line number.
now := time.Now() // get this early.
// Param to Caller is the call depth. Since this method is called from
// the Logger methods, we want the place that those were called from.
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "???"
line = 0
}
// Trim newline off format string, following usual
// Go logging conventions.
if len(message) > 0 && message[len(message)-1] == '\n' {
message = message[0 : len(message)-1]
}
formattedMessage := fmt.Sprintf(message, args...)
writeToWriters(level, logger.impl.name, file, line, now, formattedMessage)
}
// Criticalf logs the printf-formatted message at critical level.
func (logger Logger) Criticalf(message string, args ...interface{}) {
logger.Logf(CRITICAL, message, args...)
}
// Errorf logs the printf-formatted message at error level.
func (logger Logger) Errorf(message string, args ...interface{}) {
logger.Logf(ERROR, message, args...)
}
// Warningf logs the printf-formatted message at warning level.
func (logger Logger) Warningf(message string, args ...interface{}) {
logger.Logf(WARNING, message, args...)
}
// Infof logs the printf-formatted message at info level.
func (logger Logger) Infof(message string, args ...interface{}) {
logger.Logf(INFO, message, args...)
}
// Debugf logs the printf-formatted message at debug level.
func (logger Logger) Debugf(message string, args ...interface{}) {
logger.Logf(DEBUG, message, args...)
}
// Tracef logs the printf-formatted message at trace level.
func (logger Logger) Tracef(message string, args ...interface{}) {
logger.Logf(TRACE, message, args...)
}
// IsLevelEnabled returns whether debugging is enabled
// for the given log level.
func (logger Logger) IsLevelEnabled(level Level) bool {
return logger.getModule().getEffectiveLogLevel() <= level
}
// IsErrorEnabled returns whether debugging is enabled
// at error level.
func (logger Logger) IsErrorEnabled() bool {
return logger.IsLevelEnabled(ERROR)
}
// IsWarningEnabled returns whether debugging is enabled
// at warning level.
func (logger Logger) IsWarningEnabled() bool {
return logger.IsLevelEnabled(WARNING)
}
// IsInfoEnabled returns whether debugging is enabled
// at info level.
func (logger Logger) IsInfoEnabled() bool {
return logger.IsLevelEnabled(INFO)
}
// IsDebugEnabled returns whether debugging is enabled
// at debug level.
func (logger Logger) IsDebugEnabled() bool {
return logger.IsLevelEnabled(DEBUG)
}
// IsTraceEnabled returns whether debugging is enabled
// at trace level.
func (logger Logger) IsTraceEnabled() bool {
return logger.IsLevelEnabled(TRACE)
}