-
Notifications
You must be signed in to change notification settings - Fork 28
/
log.go
103 lines (89 loc) · 2.41 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
package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type logger struct {
logger *zap.SugaredLogger
filenameTrimChars int
}
var log logger
func (l *logger) GetCallerFileName(withLine bool) string {
_, filename, line, _ := runtime.Caller(2)
extension := filepath.Ext(filename)
if withLine {
return fmt.Sprint(filename[l.filenameTrimChars:len(filename)-len(extension)], "@", line)
}
return filename[l.filenameTrimChars : len(filename)-len(extension)]
}
func (l *logger) Print(a ...interface{}) {
if statusLog.isRealtime() {
statusLog.mutex.Lock()
statusLog.clearInternal()
defer func() {
statusLog.mutex.Unlock()
statusLog.print()
}()
}
l.logger.Info(append([]interface{}{l.GetCallerFileName(false) + ": "}, a...)...)
}
func (l *logger) PrintStatusLog(a ...interface{}) {
l.logger.Info(append([]interface{}{l.GetCallerFileName(false) + ": "}, a...)...)
}
func (l *logger) Debug(a ...interface{}) {
if statusLog.isRealtime() {
statusLog.mutex.Lock()
statusLog.clearInternal()
defer func() {
statusLog.mutex.Unlock()
statusLog.print()
}()
}
l.logger.Debug(append([]interface{}{l.GetCallerFileName(true) + ": "}, a...)...)
}
func (l *logger) Error(a ...interface{}) {
if statusLog.isRealtime() {
statusLog.mutex.Lock()
statusLog.clearInternal()
defer func() {
statusLog.mutex.Unlock()
statusLog.print()
}()
}
l.logger.Error(append([]interface{}{l.GetCallerFileName(true) + ": "}, a...)...)
}
func (l *logger) ErrorC(a ...interface{}) {
if statusLog.isRealtime() {
statusLog.mutex.Lock()
statusLog.clearInternal()
defer func() {
statusLog.mutex.Unlock()
statusLog.print()
}()
}
l.logger.Error(a...)
}
func (l *logger) Init() {
// Example: https://stackoverflow.com/questions/50933936/zap-logger-does-not-print-on-console-rather-print-in-the-log-file/50936341
pe := zap.NewProductionEncoderConfig()
pe.EncodeTime = zapcore.ISO8601TimeEncoder
// pe.LevelKey = ""
consoleEncoder := zapcore.NewConsoleEncoder(pe)
var level zapcore.Level
if verboseLog {
level = zap.DebugLevel
} else if quietLog {
level = zap.FatalLevel
} else {
level = zap.InfoLevel
}
core := zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), level)
l.logger = zap.New(core).Sugar()
var callerFilename string
_, callerFilename, _, _ = runtime.Caller(1)
l.filenameTrimChars = len(filepath.Dir(callerFilename)) + 1
}