-
Notifications
You must be signed in to change notification settings - Fork 9
/
logging.go
80 lines (67 loc) · 1.81 KB
/
logging.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
package tracelog
import (
"fmt"
"github.com/pkg/errors"
"io"
"io/ioutil"
"log"
"os"
)
const (
NormalLogLevel = "NORMAL"
DevelLogLevel = "DEVEL"
timeFlags = log.LstdFlags | log.Lmicroseconds
infoPrefix = "INFO: "
warningPrefix = "WARNING: "
errorPrefix = "ERROR: "
debugPrefix = "DEBUG: "
)
var InfoLogger = NewErrorLogger(os.Stdout, infoPrefix)
var WarningLogger = NewErrorLogger(os.Stdout, warningPrefix)
var ErrorLogger = NewErrorLogger(os.Stderr, errorPrefix)
var DebugLogger = NewErrorLogger(ioutil.Discard, debugPrefix)
var LogLevels = []string{NormalLogLevel, DevelLogLevel}
var logLevel = NormalLogLevel
var logLevelFormatters = map[string]string{
NormalLogLevel: "%v",
DevelLogLevel: "%+v",
}
func setupLoggers() {
if logLevel == NormalLogLevel {
DebugLogger = NewErrorLogger(ioutil.Discard, debugPrefix)
} else {
DebugLogger = NewErrorLogger(os.Stdout, debugPrefix)
}
}
type LogLevelError struct {
error
}
func NewLogLevelError() LogLevelError {
return LogLevelError{errors.Errorf("got incorrect log level: '%s', expected one of: '%v'", logLevel, LogLevels)}
}
func (err LogLevelError) Error() string {
return fmt.Sprintf(GetErrorFormatter(), err.error)
}
func GetErrorFormatter() string {
return logLevelFormatters[logLevel]
}
func UpdateLogLevel(newLevel string) error {
isCorrect := false
for _, level := range LogLevels {
if newLevel == level {
isCorrect = true
}
}
if !isCorrect {
return NewLogLevelError()
}
logLevel = newLevel
setupLoggers()
return nil
}
func RedirectLogging(infoWriter, warningWriter, errorWriter, debugWriter io.Writer) {
InfoLogger = NewErrorLogger(infoWriter, infoPrefix)
WarningLogger = NewErrorLogger(warningWriter, warningPrefix)
ErrorLogger = NewErrorLogger(errorWriter, errorPrefix)
DebugLogger = NewErrorLogger(debugWriter, debugPrefix)
}