-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
97 lines (78 loc) · 2.07 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
package log
import (
"fmt"
"io"
"os"
"github.com/v2ray/v2ray-core/common/platform"
)
const (
DebugLevel = LogLevel(0)
InfoLevel = LogLevel(1)
WarningLevel = LogLevel(2)
ErrorLevel = LogLevel(3)
)
type logger interface {
WriteLog(prefix, format string, v ...interface{})
}
type noOpLogger struct {
}
func (l *noOpLogger) WriteLog(prefix, format string, v ...interface{}) {
// Swallow
}
type streamLogger struct {
writer io.Writer
}
func (l *streamLogger) WriteLog(prefix, format string, v ...interface{}) {
var data string
if v == nil || len(v) == 0 {
data = format
} else {
data = fmt.Sprintf(format, v...)
}
l.writer.Write([]byte(prefix + data + platform.LineSeparator()))
}
var (
noOpLoggerInstance logger = &noOpLogger{}
streamLoggerInstance logger = &streamLogger{
writer: os.Stdout,
}
debugLogger = noOpLoggerInstance
infoLogger = noOpLoggerInstance
warningLogger = noOpLoggerInstance
errorLogger = noOpLoggerInstance
)
type LogLevel int
func SetLogLevel(level LogLevel) {
debugLogger = noOpLoggerInstance
if level <= DebugLevel {
debugLogger = streamLoggerInstance
}
infoLogger = noOpLoggerInstance
if level <= InfoLevel {
infoLogger = streamLoggerInstance
}
warningLogger = noOpLoggerInstance
if level <= WarningLevel {
warningLogger = streamLoggerInstance
}
errorLogger = noOpLoggerInstance
if level <= ErrorLevel {
errorLogger = streamLoggerInstance
}
}
// Debug outputs a debug log with given format and optional arguments.
func Debug(format string, v ...interface{}) {
debugLogger.WriteLog("[Debug]", format, v...)
}
// Info outputs an info log with given format and optional arguments.
func Info(format string, v ...interface{}) {
infoLogger.WriteLog("[Info]", format, v...)
}
// Warning outputs a warning log with given format and optional arguments.
func Warning(format string, v ...interface{}) {
warningLogger.WriteLog("[Warning]", format, v...)
}
// Error outputs an error log with given format and optional arguments.
func Error(format string, v ...interface{}) {
errorLogger.WriteLog("[Error]", format, v...)
}