-
Notifications
You must be signed in to change notification settings - Fork 9
/
log.go
388 lines (320 loc) · 8.49 KB
/
log.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
package toolkit
import (
//"io"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
)
type LogItem struct {
LogType string
Msg string
}
type LevelBit int
const (
AllLevel int = 0
InfoLevel = 1
WarningLevel = 2
ErrorLevel = 3
DebugLevel = 4
)
type LogEngine struct {
LogToStdOut bool
LogToFile bool
Path string
FileNamePattern string
UseDateFormat string
logInfo *log.Logger
logWarn *log.Logger
logError *log.Logger
logDebug *log.Logger
chanLogItem chan LogItem
fileNames map[string]string
writers map[string]*os.File
hooks map[string][]func(string, string)
stdOutLevels []bool
fileOutLevels []bool
prefix string
fnTemplate func(LogItem) string
//logFile *log.Logger
//logFileHandler *os.File
}
//type LogFields map[string]interface{}
func NewLog(toStdOut bool, toFile bool, path string, fileNamePattern string, useDateFormat string) (*LogEngine, error) {
var e error
l := new(LogEngine)
l.LogToStdOut = toStdOut
l.LogToFile = toFile
l.Path = path
l.FileNamePattern = fileNamePattern
l.UseDateFormat = useDateFormat
//l.logger = log.New(out, prefix, flag)
l.stdOutLevels = make([]bool, 5)
l.fileOutLevels = make([]bool, 5)
l.SetLevelStdOuts(InfoLevel, WarningLevel, ErrorLevel)
l.SetLevelFiles(InfoLevel, WarningLevel, ErrorLevel)
e = l.initLogger()
if e != nil {
return nil, e
}
if l.LogToFile {
l.chanLogItem = make(chan LogItem)
go func() {
for li := range l.chanLogItem {
l.writeLogToFile(li.Msg, li.LogType)
}
}()
}
return l, nil
}
func NewLogEngine(toStdOut bool, toFile bool, path string, fileNamePattern string, useDateFormat string) *LogEngine {
l, _ := NewLog(toStdOut, toFile, path, fileNamePattern, useDateFormat)
return l
}
func (l *LogEngine) initLogger() error {
//var e error = nil
l.initStdOut()
l.fileNames = map[string]string{}
l.writers = map[string]*os.File{}
l.hooks = map[string][]func(string, string){}
return nil
}
func (l *LogEngine) initStdOut() {
if l.LogToStdOut {
l.logError = prepareStdoutLogger(l, "ERROR")
l.logInfo = prepareStdoutLogger(l, "INFO")
l.logWarn = prepareStdoutLogger(l, "WARNING")
l.logDebug = prepareStdoutLogger(l, "DEBUG")
}
}
func prepareStdoutLogger(l *LogEngine, logType string) *log.Logger {
logger := new(log.Logger)
logger.SetFlags(0)
w := new(LogWriter)
w.initialItem = LogItem{}
w.initialItem.LogType = logType
msg := l.prefix
if l.fnTemplate == nil {
if msg != "" {
msg += " "
}
msg += "{TIME} "
msg += logType
msg += " {MSG}"
w.fn = func(item LogItem) string {
fmtMsg := msg
fmtMsg = strings.Replace(fmtMsg, "{TIME}", time.Now().Format(time.RFC3339), -1)
fmtMsg = strings.Replace(fmtMsg, "{MSG}", item.Msg, -1)
return fmtMsg
}
} else {
w.fn = l.fnTemplate
}
logger.SetOutput(w)
return logger
}
func (l *LogEngine) SetStdoutTemplate(fnTemplate func(LogItem) string) {
l.fnTemplate = fnTemplate
l.initStdOut()
}
func (l *LogEngine) HasTemplate() bool {
return l.fnTemplate != nil
}
func (l *LogEngine) SetPrefix(s string) *LogEngine {
l.prefix = s
l.initStdOut()
return l
}
func (l *LogEngine) Prefix() string {
return l.prefix
}
func (l *LogEngine) SetLevelStdOuts(levels ...int) *LogEngine {
for i := range []int{0, 1, 2, 3, 4} {
l.stdOutLevels[i] = false
}
for _, level := range levels {
if level != AllLevel {
l.stdOutLevels[AllLevel] = false
}
l.stdOutLevels[level] = true
}
return l
}
func (l *LogEngine) SetLevelStdOut(level int, value bool) *LogEngine {
if level != AllLevel {
l.stdOutLevels[AllLevel] = false
}
l.stdOutLevels[level] = value
return l
}
func (l *LogEngine) SetLevelFiles(levels ...int) *LogEngine {
for i := range []int{0, 1, 2, 3, 4} {
l.fileOutLevels[i] = false
}
for _, level := range levels {
if level != AllLevel {
l.fileOutLevels[AllLevel] = false
}
l.fileOutLevels[level] = true
}
return l
}
func (l *LogEngine) SetLevelFile(level int, value bool) *LogEngine {
if level != AllLevel {
l.fileOutLevels[AllLevel] = false
}
l.fileOutLevels[level] = value
return l
}
func (l *LogEngine) StdOutLevel(level int) bool {
return l.stdOutLevels[level]
}
func (l *LogEngine) FileOutLevel(level int) bool {
return l.fileOutLevels[level]
}
func (l *LogEngine) AddLog(msg string, logtype string) error {
var e error
logtype = strings.ToUpper(logtype)
if l.LogToStdOut {
if logtype == "ERROR" && (l.StdOutLevel(AllLevel) || l.StdOutLevel(ErrorLevel)) {
l.logError.Println(msg)
} else if logtype == "WARNING" && (l.StdOutLevel(AllLevel) || l.StdOutLevel(WarningLevel)) {
l.logWarn.Println(msg)
} else if logtype == "DEBUG" && (l.StdOutLevel(AllLevel) || l.StdOutLevel(DebugLevel)) {
l.logDebug.Println(msg)
} else if logtype == "INFO" && (l.StdOutLevel(AllLevel) || l.StdOutLevel(InfoLevel)) {
l.logInfo.Println(msg)
}
if e != nil {
return errors.New("Log.AddLog Error: " + e.Error())
}
}
if l.LogToFile {
l.chanLogItem <- LogItem{logtype, msg}
}
//--- run hook
go func() {
hooks := l.hooks[logtype]
for _, hook := range hooks {
hook(logtype, msg)
}
}()
return nil
}
func (l *LogEngine) writeLogToFile(msg, logtype string) {
if logtype == "ERROR" && !l.FileOutLevel(AllLevel) && !l.FileOutLevel(ErrorLevel) {
return
} else if logtype == "WARNING" && !l.FileOutLevel(AllLevel) && !l.FileOutLevel(WarningLevel) {
return
} else if logtype == "INFO" && !l.FileOutLevel(AllLevel) && !l.FileOutLevel(InfoLevel) {
return
} else if logtype == "DEBUG" && !l.FileOutLevel(AllLevel) && !l.FileOutLevel(DebugLevel) {
return
}
filename := l.FileNamePattern
if l.UseDateFormat != "" && strings.Contains(l.FileNamePattern, "$DATE") {
filename = strings.Replace(l.FileNamePattern, "$DATE", Date2String(time.Now(), l.UseDateFormat), -1)
}
if strings.Contains(filename, "$LOGTYPE") {
filename = strings.Replace(filename, "$LOGTYPE", logtype, -1)
}
filename = filepath.Join(l.Path, filename)
filenameSelected := l.fileNames[logtype]
if filename != filenameSelected {
w, exist := l.writers[logtype]
if exist {
w.Close()
}
f, e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
if e != nil {
return
//return errors.New("Log.AddLog Error: " + e.Error())
}
l.fileNames[logtype] = filename
l.writers[logtype] = f
}
if l.prefix == "" {
logFile := log.New(l.writers[logtype], logtype+" ", log.Ldate|log.Ltime)
logFile.Println(msg)
} else {
logFile := log.New(l.writers[logtype], l.prefix+" "+logtype+" ", log.Ldate|log.Ltime)
logFile.Println(msg)
}
}
func (l *LogEngine) AddHook(fn func(string, string), logtypes ...string) {
if len(logtypes) == 0 {
logtypes = []string{"ERROR", "INFO", "WARNING", "DEBUG"}
}
for _, logtype := range logtypes {
hooks := l.hooks[logtype]
hooks = append(hooks, fn)
l.hooks[logtype] = hooks
}
}
func (l *LogEngine) Debug(msg string) error {
return l.AddLog(msg, "DEBUG")
}
func (l *LogEngine) Info(msg string) error {
return l.AddLog(msg, "INFO")
}
func (l *LogEngine) Error(msg string) error {
return l.AddLog(msg, "ERROR")
}
func (l *LogEngine) Warning(msg string) error {
return l.AddLog(msg, "WARNING")
}
func (l *LogEngine) Infof(msg string, args ...interface{}) error {
msg = Sprintf(msg, args...)
return l.AddLog(msg, "INFO")
}
func (l *LogEngine) Errorf(msg string, args ...interface{}) error {
msg = Sprintf(msg, args...)
return l.AddLog(msg, "ERROR")
}
func (l *LogEngine) Warningf(msg string, args ...interface{}) error {
msg = Sprintf(msg, args...)
return l.AddLog(msg, "WARNING")
}
func (l *LogEngine) Debugf(msg string, args ...interface{}) error {
msg = Sprintf(msg, args...)
return l.AddLog(msg, "DEBUG")
}
func (l *LogEngine) Close() {
//l.logFileHandler.Close()
for _, w := range l.writers {
w.Close()
}
if l.chanLogItem != nil {
close(l.chanLogItem)
}
}
// Error2 will send msg1 to output log and msg2 to system, it could be useful for logging something that can only be seen by sysadmin and user
func (l *LogEngine) Error2(msg1, msg2 string, parm ...interface{}) error {
l.Errorf(msg2, parm...)
return errors.New(msg1)
}
/* deprecated
func LogM(m M, msg string) string {
return Sprintf("field:%s message:%s",
JsonString(m), msg)
}
*/
var _logger *LogEngine
func Logger() *LogEngine {
if _logger == nil {
_logger, _ = NewLog(true, false, "", "", "")
}
return _logger
}
type LogWriter struct {
initialItem LogItem
fn func(item LogItem) string
}
func (w *LogWriter) Write(bs []byte) (int, error) {
item := w.initialItem
item.Msg = string(bs)
return fmt.Print(w.fn(item))
}