/
logger.go
130 lines (105 loc) · 2.48 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
// Logging provider
//
// Log only fully init when app.Run() called
package logger
import (
"fmt"
"github.com/sirupsen/logrus"
"log"
"runtime"
"strings"
)
type Fields logrus.Fields
var currentServLog ServiceLogger
func InitServLogger(allowFileLogger bool) {
if allowFileLogger {
currentServLog = DefaultMessageLogger
} else {
currentServLog = DefaultStdLogger
}
}
func GetCurrent() ServiceLogger {
return currentServLog
}
type Logger interface {
Print(args ...interface{})
Debug(...interface{})
Debugln(...interface{})
Debugf(string, ...interface{})
Info(...interface{})
Infoln(...interface{})
Infof(string, ...interface{})
Warn(...interface{})
Warnln(...interface{})
Warnf(string, ...interface{})
Error(...interface{})
Errorln(...interface{})
Errorf(string, ...interface{})
Fatal(...interface{})
Fatalln(...interface{})
Fatalf(string, ...interface{})
Panic(...interface{})
Panicln(...interface{})
Panicf(string, ...interface{})
With(key string, value interface{}) Logger
Withs(Fields) Logger
// add source field to log
WithSrc() Logger
GetLevel() string
}
type logger struct {
*logrus.Entry
}
func (l *logger) GetLevel() string {
return l.Entry.Logger.Level.String()
}
func (l *logger) debugSrc() *logrus.Entry {
if _, ok := l.Entry.Data["source"]; ok {
return l.Entry
}
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
file = file[slash+1:]
}
return l.Entry.WithField("source", fmt.Sprintf("%s:%d", file, line))
}
func (l *logger) Debug(args ...interface{}) {
if l.Entry.Logger.Level >= logrus.DebugLevel {
l.debugSrc().Debug(args...)
}
}
func (l *logger) Debugln(args ...interface{}) {
if l.Entry.Logger.Level >= logrus.DebugLevel {
l.debugSrc().Debugln(args...)
}
}
func (l *logger) Debugf(format string, args ...interface{}) {
if l.Entry.Logger.Level >= logrus.DebugLevel {
l.debugSrc().Debugf(format, args...)
}
}
func (l *logger) Print(args ...interface{}) {
if l.Entry.Logger.Level >= logrus.DebugLevel {
l.debugSrc().Debug(args)
}
}
func (l *logger) With(key string, value interface{}) Logger {
return &logger{l.Entry.WithField(key, value)}
}
func (l *logger) Withs(fields Fields) Logger {
return &logger{l.Entry.WithFields(logrus.Fields(fields))}
}
func (l *logger) WithSrc() Logger {
return &logger{l.debugSrc()}
}
func mustParseLevel(level string) logrus.Level {
lv, err := logrus.ParseLevel(level)
if err != nil {
log.Fatal(err.Error())
}
return lv
}