-
Notifications
You must be signed in to change notification settings - Fork 290
/
log.go
124 lines (103 loc) · 2.14 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
package logger
import (
"fmt"
"io"
"os"
"runtime"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh/terminal"
)
const (
nocolor = "0"
red = "31"
green = "1;32"
yellow = "33"
blue = "34"
gray = "1;30"
cyan = "1;36"
)
var level = INFO
var colors = true
var mutex = sync.Mutex{}
func GetLevel() Level {
return level
}
func SetLevel(l Level) {
level = l
if level == DEBUG {
Debug("Debug mode enabled")
}
}
func SetColors(b bool) {
colors = b
}
func ColorsEnabled() bool {
if runtime.GOOS == "windows" {
// Boo, no colors on Windows.
return false
} else {
// Colors can only be shown if STDOUT is a terminal
if terminal.IsTerminal(int(os.Stdout.Fd())) {
return colors
} else {
return false
}
}
}
func OutputPipe() io.Writer {
// All logging, all the time, goes to STDERR
return os.Stderr
}
func Debug(format string, v ...interface{}) {
if level == DEBUG {
log(DEBUG, format, v...)
}
}
func Error(format string, v ...interface{}) {
log(ERROR, format, v...)
}
func Fatal(format string, v ...interface{}) {
log(FATAL, format, v...)
os.Exit(1)
}
func Notice(format string, v ...interface{}) {
log(NOTICE, format, v...)
}
func Info(format string, v ...interface{}) {
log(INFO, format, v...)
}
func Warn(format string, v ...interface{}) {
log(WARN, format, v...)
}
func log(l Level, format string, v ...interface{}) {
level := strings.ToUpper(l.String())
message := fmt.Sprintf(format, v...)
now := time.Now().Format("2006-01-02 15:04:05")
line := ""
if ColorsEnabled() {
prefixColor := green
messageColor := nocolor
if l == DEBUG {
prefixColor = gray
messageColor = gray
} else if l == NOTICE {
prefixColor = cyan
} else if l == WARN {
prefixColor = yellow
} else if l == ERROR {
prefixColor = red
} else if l == FATAL {
prefixColor = red
messageColor = red
}
line = fmt.Sprintf("\x1b[%sm%s %-6s\x1b[0m \x1b[%sm%s\x1b[0m\n", prefixColor, now, level, messageColor, message)
} else {
line = fmt.Sprintf("%s %-6s %s\n", now, level, message)
}
// Make sure we're only outputing a line one at a time
mutex.Lock()
fmt.Fprint(OutputPipe(), line)
mutex.Unlock()
}