-
Notifications
You must be signed in to change notification settings - Fork 9
/
mylog.go
128 lines (109 loc) · 2.46 KB
/
mylog.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
package mylog
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
type Logger interface {
Printf(string, ...interface{})
}
type Level int
const (
LevelFatal Level = -2
LevelError = iota
LevelInfo
LevelTrace
LevelDebug
)
var levelStrings = map[string]Level{
"FATAL": LevelFatal,
"ERROR": LevelError,
"INFO": LevelInfo,
"TRACE": LevelTrace,
"DEBUG": LevelDebug,
}
var prefixes = map[Level]string{
LevelFatal: "[FATAL] ",
LevelError: "[ERROR] ",
LevelInfo: "[INFO ] ",
LevelTrace: "[TRACE] ",
LevelDebug: "[DEBUG] ",
}
type MyLog struct {
logLevel Level
logger Logger
}
// NewLog return a MyLog structure
func NewLog(lvl string, logger Logger) (*MyLog, error) {
var (
level Level
ok bool
)
if level, ok = levelStrings[strings.ToUpper(lvl)]; !ok {
return nil, fmt.Errorf("Invalid log level '%s'", lvl)
}
// intercept all direct call to log as in http package
log.SetOutput(ioutil.Discard)
return &MyLog{
logLevel: level,
logger: logger,
}, nil
}
// Fatal prepare the output of FATAL message
func (l *MyLog) Fatal() logcontext {
return logcontext{l, LevelFatal}
}
// Error prepare the output of ERROR message
func (l *MyLog) Error() logcontext {
return logcontext{l, LevelError}
}
// Info prepare the output of INFO message
func (l *MyLog) Info() logcontext {
return logcontext{l, LevelInfo}
}
// Trace prepare the output of TRACE message
func (l *MyLog) Trace() logcontext {
return logcontext{l, LevelTrace}
}
// Debug prepare the output of DEBUG message
func (l *MyLog) Debug() logcontext {
return logcontext{l, LevelDebug}
}
// IsDebug return true if log level is DEBUG
func (l *MyLog) IsDebug() bool {
if l == nil {
return true
}
return l.logLevel >= LevelDebug
}
// logcontext get the level of current message
type logcontext struct {
mylog *MyLog
lvl Level
}
// Printf print message on configured writers
// When a log file writer is provided, only errors are written on
// console writer
// When the message is FATAL, the message is written on writers and the
// program exits
// If the logger isn't initialized, it logs to the console
func (c logcontext) Printf(fmt string, args ...interface{}) {
if c.mylog == nil {
if c.lvl == LevelFatal {
log.Fatalf(prefixes[c.lvl]+fmt, args...)
} else {
log.Printf(prefixes[c.lvl]+fmt, args...)
}
return
}
if c.lvl <= c.mylog.logLevel {
if c.mylog.logger != nil {
c.mylog.logger.Printf(prefixes[c.lvl]+fmt, args...)
}
}
if c.lvl == LevelFatal {
os.Exit(1)
}
}