forked from Tinsane/tracelog
-
Notifications
You must be signed in to change notification settings - Fork 7
/
logging.go
86 lines (71 loc) · 1.95 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
81
82
83
84
85
86
package tracelog
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/pkg/errors"
)
const (
NormalLogLevel = "NORMAL"
DevelLogLevel = "DEVEL"
ErrorLogLevel = "ERROR"
timeFlags = log.LstdFlags | log.Lmicroseconds
)
var InfoLogger = NewErrorLogger(os.Stderr, "INFO: ")
var WarningLogger = NewErrorLogger(os.Stderr, "WARNING: ")
var ErrorLogger = NewErrorLogger(os.Stderr, "ERROR: ")
var DebugLogger = NewErrorLogger(ioutil.Discard, "DEBUG: ")
var LogLevels = []string{NormalLogLevel, DevelLogLevel, ErrorLogLevel}
var logLevel = NormalLogLevel
var logLevelFormatters = map[string]string{
NormalLogLevel: "%v",
ErrorLogLevel: "%v",
DevelLogLevel: "%+v",
}
func setupLoggers() {
if logLevel == NormalLogLevel {
DebugLogger = NewErrorLogger(ioutil.Discard, "DEBUG: ")
} else if logLevel == ErrorLogLevel {
DebugLogger = NewErrorLogger(ioutil.Discard, "DEBUG: ")
InfoLogger = NewErrorLogger(ioutil.Discard, "INFO: ")
WarningLogger = NewErrorLogger(ioutil.Discard, "WARNING: ")
} else {
DebugLogger = NewErrorLogger(os.Stderr, "DEBUG: ")
}
}
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 SetInfoOutput(destination *os.File) {
InfoLogger = NewErrorLogger(destination, "INFO: ")
}
func SetWarningOutput(destination *os.File) {
WarningLogger = NewErrorLogger(destination, "WARNING: ")
}
func SetErrorOutput(destination *os.File) {
ErrorLogger = NewErrorLogger(destination, "ERROR: ")
}