-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
137 lines (113 loc) · 2.39 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
package log
import (
"fmt"
"io"
"os"
osPath "path"
"time"
logging "github.com/sirupsen/logrus"
)
const (
PANIC = "panic"
FATAL = "fatal"
ERROR = "error"
WARN = "warn"
INFO = "info"
DEBUG = "debug"
TRACE = "trace"
)
var (
_ = Trace
_ = Debug
_ = Info
_ = Warn
_ = Error
_ = Fatal
_ = InitLogger
_ = PANIC
_ = FATAL
_ = ERROR
_ = WARN
_ = INFO
_ = DEBUG
_ = TRACE
)
func InitLogger(path, logPrefix, logLevel string, shouldSave bool) error {
if shouldSave {
file, err := os.OpenFile(
getLogFileDir(path, logPrefix),
os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666,
)
if err != nil {
return err
}
mw := io.MultiWriter(file, os.Stdout)
logging.SetOutput(mw)
}
logging.SetFormatter(&Formatter{})
lvl, err := logging.ParseLevel(logLevel)
if err != nil {
return err
}
logging.SetLevel(lvl)
return nil
}
func Trace(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Trace(message)
return
}
logging.Trace(message)
}
func Debug(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Debug(message)
return
}
logging.Debug(message)
}
func Info(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Info(message)
return
}
logging.Info(message)
}
func Warn(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Warn(message)
return
}
logging.Warn(message)
}
func Error(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Error(message)
return
}
logging.Error(message)
}
func Fatal(message string, params ...interface{}) {
if hasParseableFields(params...) {
logging.WithFields(makeFields(params...)).Fatal(message)
return
}
logging.Fatal(message)
}
func makeFields(params ...interface{}) logging.Fields {
m := make(logging.Fields)
for i := 0; i < len(params); i += 2 {
k, ok := params[i].(string)
if !ok {
continue
}
m[k] = params[i+1]
}
return m
}
func hasParseableFields(params ...interface{}) bool {
return len(params) != 0 && len(params)%2 == 0
}
func getLogFileDir(path, filePrefix string) string {
return osPath.Join(path, fmt.Sprintf("%s-%s.log", filePrefix, time.Now().UTC().Format(time.RFC822)))
}