-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
139 lines (112 loc) · 2.4 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
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
package log
import (
"fmt"
"io"
"os"
"sync"
"github.com/fatih/color"
)
type (
Level int
prefixerInterface interface {
Prefix() string
}
defaultPrefixer struct{}
)
const (
LevelDebug Level = iota
LevelTask
LevelWarn
LevelAlert
LevelError
)
var (
Yellow = color.New(color.FgYellow, color.Bold).SprintFunc()
Red = color.New(color.FgHiRed, color.Bold).SprintFunc()
Purple = color.New(color.FgMagenta, color.Bold).SprintFunc()
Green = color.New(color.FgGreen, color.Bold).SprintFunc()
WhiteOnRed = color.New(color.FgWhite, color.BgRed, color.Bold).SprintFunc()
Dark = color.New(color.FgHiBlack).SprintFunc()
BoldWhite = color.New(color.FgHiWhite, color.Bold).SprintFunc()
channel io.Writer = os.Stderr
logLevel = LevelDebug
writeLock sync.Mutex
prefixer prefixerInterface = defaultPrefixer{}
)
func (p defaultPrefixer) Prefix() string {
return ""
}
func SetPrefixer(p prefixerInterface) {
prefixer = p
}
func Silence(new bool) bool {
prev := channel == io.Discard
if new {
channel = io.Discard
} else {
channel = os.Stderr
}
return prev
}
func SetLevel(l Level) {
logLevel = l
}
func init() {
// color.NoColor = false // Override terminal detection
}
func Debug(arg ...interface{}) {
if logLevel <= LevelDebug {
_print(Dark(" "), arg...)
}
}
func Task(arg ...interface{}) {
if logLevel <= LevelTask {
_print(Yellow(">>>"), arg...)
}
}
func Warn(arg ...interface{}) {
if logLevel <= LevelWarn {
_print(Red("!!!"), arg...)
}
}
func Alert(arg ...interface{}) {
if logLevel <= LevelAlert {
_print(Purple(" ! "), arg...)
}
}
func Ok(arg ...interface{}) {
if logLevel <= LevelTask {
_print(Green(" ✔ "), arg...)
}
}
func Progress(arg ...interface{}) {
if logLevel <= LevelTask {
_print(" - ", arg...)
}
}
func Fatal(arg ...interface{}) {
_print(WhiteOnRed("XXX"), arg...)
os.Exit(1)
}
func Fatalf(format string, arg ...interface{}) {
Fatal(fmt.Sprintf(format, arg...))
}
func Check(e error, msg ...interface{}) {
if e != nil {
if len(msg) > 0 {
_print("ERR", msg...)
}
Fatal(e.Error())
}
}
func Error(e error) {
Fatal("Fatal error:", e.Error())
}
func Errorf(format string, arg ...interface{}) {
Fatal(fmt.Errorf(format, arg...))
}
func _print(prefix string, arg ...interface{}) {
writeLock.Lock()
defer writeLock.Unlock()
fmt.Fprintf(channel, "%s %s %s", prefixer.Prefix(), prefix, fmt.Sprintln(arg...))
}