forked from visionmedia/go-debug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debug.go
387 lines (324 loc) · 8.05 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
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package debug
import (
"fmt"
"io"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/nmccready/colorjson"
goCache "github.com/patrickmn/go-cache"
)
var (
writer io.Writer = os.Stderr
reg *regexp.Regexp
neg []*regexp.Regexp
m sync.Mutex
enabled = false
cache *goCache.Cache
HAS_COLORS = true
HAS_TIME = true
defaultFormatter = &TextFormatter{HasColor: true}
formatter Formatter = defaultFormatter
negRegEx = regexp.MustCompile(`^-.*?`)
jsonRegex = regexp.MustCompile(`(?i)json`)
)
type Fields map[string]interface{}
type Debugger struct {
name string
prev time.Time
fields Fields
color string
// mu MutexWrap
}
type IDebugger interface {
Log(...interface{})
Error(...interface{})
Warn(...interface{})
Spawn(ns string) *Debugger
WithFields(fields Fields) *Debugger
WithField(key string, value interface{}) *Debugger
}
// Terminal colors used at random.
var colors []string = []string{"31", "32", "33", "34", "35", "36", "91", "92", "93", "94", "95", "96"}
// Initialize with DEBUG environment variable.
func init() {
env := os.Getenv("DEBUG")
cacheMinStr := os.Getenv("DEBUG_CACHE_MINUTES")
colorOffStr := os.Getenv("DEBUG_COLOR_OFF")
timeOffStr := os.Getenv("DEBUG_TIME_OFF")
if "" != env {
Enable(env)
}
SetHasColors(colorOffStr == "")
SetHasTime(timeOffStr == "")
SetFormatterString(os.Getenv("DEBUG_FORMATTER")) // after HAS_COLOR and HAS_TIME on purpose
err := SetCache(cacheMinStr)
if err != nil {
panic(err)
}
}
// SetWriter replaces the default of os.Stderr with `w`.
func SetWriter(w io.Writer) {
m.Lock()
defer m.Unlock()
writer = w
}
// Disable all pattern matching. This function is thread-safe.
func Disable() {
m.Lock()
defer m.Unlock()
enabled = false
}
func SetFormatter(f Formatter) {
if f == nil {
f = defaultFormatter
}
m.Lock()
defer m.Unlock()
formatter = f
}
func SetFormatterString(s string) {
var _f Formatter = &TextFormatter{HasColor: HAS_COLORS}
if s == "" {
return
}
if jsonRegex.MatchString(s) {
// default to PRETTY true
jf := &JSONFormatter{
PrettyPrint: os.Getenv("DEBUG_FORMATTER_PRETTY_OFF") == "",
FlattenMsgFields: os.Getenv("DEBUG_FORMATTER_FLATTEN_FIELDS") != "",
}
indent := os.Getenv("DEBUG_FORMATTER_INDENT")
if indent != "" {
i, err := strconv.Atoi(indent)
if err != nil {
panic(err)
}
jf.Indent = i
}
_f = jf
}
SetFormatter(_f)
}
/*
Enable the given debug `pattern`. Patterns take a glob-like form,
for example if you wanted to enable everything, just use "*", or
if you had a library named mongodb you could use "mongodb:connection",
or "mongodb:*". Multiple matches can be made with a comma, for
example "mongo*,redis*".
This function is thread-safe.
*/
func Enable(pattern string) {
m.Lock()
defer m.Unlock()
pattern, neg = BuildPattern(pattern)
reg = regexp.MustCompile(pattern)
enabled = true
}
func BuildPattern(pattern string) (string, []*regexp.Regexp) {
pattern = regexp.QuoteMeta(pattern)
pattern = RegExWildCard(pattern)
pattern = strings.Replace(pattern, ",", "|", -1)
pattern, negatives := BuildNegativeMatches(pattern, `|`)
return RegExWrap(pattern), negatives
}
func RegExWildCard(pattern string) string {
return strings.Replace(pattern, "\\*", ".*?", -1)
}
func RegExWrap(pattern string) string {
return "^(" + pattern + ")$"
}
func RegExWrapCompile(pattern string) *regexp.Regexp {
return regexp.MustCompile(RegExWrap(pattern))
}
/*
Find all negative namespaces and pull them out of the pattern.
But build a slice of negatives
example: pattern="*,-somenamespace"
Returns: "*", ["somenamespace"]
*/
func BuildNegativeMatches(pattern string, orString string) (string, []*regexp.Regexp) {
if orString == "" {
orString = ","
}
var negatives []*regexp.Regexp
maybeNegs := strings.Split(pattern, orString)
// fmt.Printf("maybeNegs: %+v\n", maybeNegs)
for _, s := range maybeNegs {
if negRegEx.MatchString(s) {
negatives = append(negatives, RegExWrapCompile(strings.Replace(s, "-", "", 1)))
pattern = strings.Replace(pattern, orString+s, "", -1)
}
}
return pattern, negatives
}
/*
Initialize the namespace cache which defaults to 60 min lifespan
*/
func SetCache(cacheMinStr string) error {
var err error
cachedMin := 60
m.Lock()
defer m.Unlock()
if cacheMinStr != "" {
cachedMin, err = strconv.Atoi(cacheMinStr)
if err != nil {
return err
}
}
cache = goCache.New(time.Duration(cachedMin)*time.Minute, 10*time.Minute)
return nil
}
func setBoolWithLock(work func(bool)) func(bool) {
return func(isOn bool) {
m.Lock()
defer m.Unlock()
work(isOn)
}
}
var SetHasColors = setBoolWithLock(func(isOn bool) {
HAS_COLORS = isOn
})
var SetHasTime = setBoolWithLock(func(isOn bool) {
HAS_TIME = isOn
})
func (dbg Debugger) ApplyRootFields(name string) Debugger {
if formatter.GetHasFieldsOnly() {
dbg = *dbg.WithFields(map[string]interface{}{"namespace": name})
if HAS_TIME {
dbg = *dbg.WithFields(map[string]interface{}{"time": nil, "delta": nil})
}
}
return dbg
}
// Debug creates a debug function for `name` which you call
// with printf-style arguments in your application or library.
func Debug(name string) Debugger {
entry, cached := cache.Get(name)
if cached {
dbg, _ := entry.(Debugger)
return dbg.ApplyRootFields(name)
}
dbg := Debugger{name: name, prev: time.Now(), color: colors[rand.Intn(len(colors))]}
dbg = dbg.ApplyRootFields(name)
cache.Set(name, dbg, goCache.DefaultExpiration)
return dbg
}
func (dbg Debugger) Spawn(ns string) *Debugger {
d := Debug(dbg.name + ":" + ns)
d.fields = dbg.fields
return &d
}
func (dbg Debugger) Log(args ...interface{}) {
if !enabled {
return
}
if !reg.MatchString(dbg.name) {
return
}
for _, n := range neg {
if n.MatchString(dbg.name) {
return
}
}
// dbg.mu.Lock()
var msg interface{}
if len(args) >= 1 {
arg0 := args[0]
args = args[1:]
switch v := arg0.(type) {
case string:
msg = v
case Fields, colorjson.Object, map[string]interface{}:
msg = v
case func() string:
msg = v()
case func() Fields:
msg = v()
case func() colorjson.Object:
msg = v()
case func() map[string]interface{}:
msg = v()
default:
// coerce to string
msg = fmt.Sprint(v)
}
}
preppedMsg := formatter.Format(dbg, msg)
fmt.Fprintf(writer, preppedMsg, args...)
dbg.prev = time.Now()
}
// prepend error/warn name as it is easier to filter!
func (dbg Debugger) Error(args ...interface{}) {
d := Debug("error:" + dbg.name)
d.fields = dbg.fields
d.Log(args...)
}
func (dbg Debugger) Warn(args ...interface{}) {
d := Debug("warn:" + dbg.name)
d.fields = dbg.fields
d.Log(args...)
}
// NOT *Debugger receiver on purpose to be immutable to not deal with locks on fields
func (dbg Debugger) WithFields(fields Fields) *Debugger {
data := make(Fields, len(dbg.fields)+len(fields))
for k, v := range dbg.fields {
data[k] = v
}
for k, v := range fields {
data[k] = v
}
dbg.fields = data
return &dbg
}
// NOT *Debugger receiver on purpose to be immutable to not deal with locks on fields
func (dbg Debugger) WithField(key string, value interface{}) *Debugger {
return dbg.WithFields(Fields{key: value})
}
func getColorStr(color string, isOn bool) string {
if !isOn {
return ""
}
return "\033[" + color + "m"
}
func getColorOff(isOn bool) string {
if !isOn {
return ""
}
return "\033[0m"
}
func getTime(timestring string, delta string, isOn bool) string {
if !isOn {
return ""
}
return fmt.Sprintf("%s %-6s", timestring, delta)
}
// Return formatting for deltas.
func deltas(prev time.Time) (string, string) {
now := time.Now()
delta := now.Sub(prev).Nanoseconds()
ts := now.UTC().Format("15:04:05.000")
return ts, humanizeNano(delta)
}
// Humanize nanoseconds to a string.
func humanizeNano(n int64) string {
var suffix string
switch {
case n > 1e9:
n /= 1e9
suffix = "s"
case n > 1e6:
n /= 1e6
suffix = "ms"
case n > 1e3:
n /= 1e3
suffix = "us"
default:
suffix = "ns"
}
return strconv.Itoa(int(n)) + suffix
}