-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdebug.go
107 lines (85 loc) · 2.47 KB
/
debug.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
// package debugger provides an environment based logger
//
// In order for logs to display, the DEBUG environment variable must be set and
// match the key provided to debugger.NewDebugger
//
// DEBUG may be set as a comma-separated list, and also supports wildcards matching (*).
package debugger
import (
"fmt"
"os"
"strings"
"strconv"
"regexp"
"time"
"github.com/mgutz/ansi"
)
var (
// Compile collection of regular expressions corresponding to Debug
debug_r []*regexp.Regexp
base = "\033[1;30m"
reset = ansi.ColorCode("reset")
colors = []string{ "red", "magenta", "blue", "green", "cyan", "yellow" }
max = 5
last = 0
)
type (
// Debugger provides logging based on DEBUG environment variable
//
// If the provided debugger key is found to be a match for the environment, logs will be displayed.
Debugger interface {
// Log will output log message to stdout, prefixed with key
Log (vals ...interface{})
}
validDebugger struct {
key string
last time.Time
first bool
print func(string) string
}
invalidDebugger struct {}
)
// NewDebugger provides creates a new Debugger based the provided key. Each debugger will
// be assigned a different color, up to five colors, then repeat.
//
// key will be compared with the environment variable "DEBUG" in order to determine if logs
// should be output.
func NewDebugger (key string) Debugger {
// Determine type of Debugger to deliver based on environment
for _, r := range(debug_r) {
if r.String() != "" && r.MatchString(key) {
color := colors[last]
last = (last + 1) % 5
// Valid debug
return &validDebugger{ key, time.Time{}, true, ansi.ColorFunc(color) }
}
}
// Invalid debug
return &invalidDebugger{}
}
// validDebugger.Log will output if match
func (l *validDebugger) Log (vals ...interface{}) {
// Determine time since last log
diff := time.Since(l.last) / 1e6
// Check if first log, always 0ms
if l.first {
diff = 0
l.first = false
}
// Capture time of log
l.last = time.Now()
// Build log
log := append([]interface{}{ l.print(l.key), base }, append(vals, reset, l.print(strconv.Itoa(int(diff)) + "ms"))...)
// Send log
fmt.Println(log...)
}
// invalidDebugger.Log will never output
func (l invalidDebugger) Log (vals ...interface{}) {}
func init () {
// Grab environment and parse into regex's
debug := strings.Split(os.Getenv("DEBUG"), ",")
for _, val := range(debug) {
r, _ := regexp.Compile("^" + strings.Replace(val, "*", ".*?", -1) + "$")
debug_r = append(debug_r, r)
}
}