forked from oracleNetworkProtocol/plugchain-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
113 lines (91 loc) · 2.35 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
package log
import (
"io"
"os"
"strings"
"github.com/sirupsen/logrus"
"github.com/tendermint/tendermint/libs/log"
)
var (
_ log.Logger = LogrusLogger{}
_ log.Logger = entry{}
)
type LogrusLogger struct {
logger *logrus.Logger
}
func NewDefaultLogger() LogrusLogger {
logger := logrus.New()
logger.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
logger.SetOutput(os.Stdout)
logger.SetLevel(logrus.InfoLevel)
return LogrusLogger{
logger: logger,
}
}
func NewLogger(cfg Config) LogrusLogger {
logger := logrus.New()
switch cfg.Format {
case FormatText:
logger.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
case FormatJSON:
logger.SetFormatter(&logrus.JSONFormatter{})
}
switch strings.ToLower(cfg.Level) {
case DebugLevel:
logger.SetLevel(logrus.DebugLevel)
case InfoLevel:
logger.SetLevel(logrus.InfoLevel)
case WarnLevel:
logger.SetLevel(logrus.WarnLevel)
case ErrorLevel:
logger.SetLevel(logrus.ErrorLevel)
}
logger.SetOutput(os.Stdout)
return LogrusLogger{
logger: logger,
}
}
func (l *LogrusLogger) SetOutput(output io.Writer) {
l.logger.SetOutput(os.Stdout)
}
func (l LogrusLogger) Debug(msg string, keyvals ...interface{}) {
l.logger.WithFields(argsToFields(keyvals...)).Debug(msg)
}
func (l LogrusLogger) Info(msg string, keyvals ...interface{}) {
l.logger.WithFields(argsToFields(keyvals...)).Info(msg)
}
func (l LogrusLogger) Error(msg string, keyvals ...interface{}) {
l.logger.WithFields(argsToFields(keyvals...)).Error(msg)
}
func (l LogrusLogger) With(keyvals ...interface{}) log.Logger {
return entry{
l.logger.WithFields(argsToFields(keyvals...)),
}
}
type entry struct {
*logrus.Entry
}
func (e entry) Debug(msg string, keyvals ...interface{}) {
e.Entry.WithFields(argsToFields(keyvals...)).Debug(msg)
}
func (e entry) Info(msg string, keyvals ...interface{}) {
e.Entry.WithFields(argsToFields(keyvals...)).Info(msg)
}
func (e entry) Error(msg string, keyvals ...interface{}) {
e.Entry.WithFields(argsToFields(keyvals...)).Error(msg)
}
func (e entry) With(keyvals ...interface{}) log.Logger {
return entry{
e.WithFields(argsToFields(keyvals...)),
}
}
func argsToFields(keyvals ...interface{}) logrus.Fields {
var fields = make(logrus.Fields)
if len(keyvals)%2 != 0 {
return fields
}
for i := 0; i < len(keyvals); i += 2 {
fields[keyvals[i].(string)] = keyvals[i+1]
}
return fields
}