-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.go
154 lines (124 loc) · 2.41 KB
/
logging.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
package logging
import (
"fmt"
"log"
"os"
"strings"
)
type Level int
var (
std = NewLogger()
)
type Logger struct {
Level Level
*log.Logger
contextMessage string
}
const (
ErrorLevel = 0
InfoLevel = 1
DebugLevel = 2
)
func getLevel(l string) Level {
switch strings.ToLower(l) {
case "error":
return ErrorLevel
case "debug":
return DebugLevel
case "info":
return InfoLevel
default:
return InfoLevel
}
}
func NewLogger() *Logger {
level, ok := os.LookupEnv("LOG_LEVEL")
if ok {
level = os.Getenv("LOG_LEVEL")
}
l := getLevel(level)
logger := log.Default()
return &Logger{
l,
logger,
"",
}
}
func (l *Logger) log(lvl Level, s interface{}) {
if lvl <= l.Level {
if l.contextMessage != "" {
l.Printf("%s [%s]\n", s, l.contextMessage)
} else {
l.Println(s)
}
}
}
func (l *Logger) clone() *Logger {
copy := *l
return ©
}
func (l *Logger) WithContext(s string) *Logger {
c := l.clone()
c.contextMessage = s
return c
}
func (l *Logger) Error(s interface{}) {
m := fmt.Sprintf("[ERROR] %s", s)
l.log(ErrorLevel, m)
}
func (l *Logger) Errorf(format string, s ...interface{}) {
f := fmt.Sprintf("[ERROR] %s", format)
m := fmt.Sprintf(f, s...)
l.log(ErrorLevel, m)
}
func (l *Logger) Info(s interface{}) {
m := fmt.Sprintf("[INFO] %s", s)
l.log(InfoLevel, m)
}
func (l *Logger) Infof(format string, s ...interface{}) {
f := fmt.Sprintf("[INFO] %s", format)
m := fmt.Sprintf(f, s...)
l.log(InfoLevel, m)
}
func (l *Logger) Debug(s interface{}) {
m := fmt.Sprintf("[DEBUG] %s", s)
l.log(DebugLevel, m)
}
func (l *Logger) Debugf(format string, s ...interface{}) {
f := fmt.Sprintf("[DEBUG] %s", format)
m := fmt.Sprintf(f, s...)
l.log(DebugLevel, m)
}
func (l *Logger) Fatal(s interface{}) {
m := fmt.Sprintf("[FATAL] %s", s)
l.Logger.Fatal(m)
}
func (l *Logger) Fatalf(format string, s ...interface{}) {
f := fmt.Sprintf("[FATAL] %s", format)
m := fmt.Sprintf(f, s...)
l.Logger.Fatalf(format, m)
}
func Error(s interface{}) {
std.Error(s)
}
func Errorf(format string, s ...interface{}) {
std.Errorf(format, s...)
}
func Info(s interface{}) {
std.Info(s)
}
func Infof(format string, s ...interface{}) {
std.Infof(format, s...)
}
func Debug(s interface{}) {
std.Debug(s)
}
func Debugf(format string, s ...interface{}) {
std.Debugf(format, s...)
}
func Fatal(s interface{}) {
std.Fatal(s)
}
func Fatalf(format string, s ...interface{}) {
std.Fatalf(format, s...)
}