-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebugo.go
More file actions
89 lines (65 loc) · 1.44 KB
/
debugo.go
File metadata and controls
89 lines (65 loc) · 1.44 KB
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
package debugo
import (
"encoding/json"
"io"
"maps"
"sync"
"time"
"github.com/fatih/color"
)
func init() {
color.NoColor = false
}
type Debugger struct {
namespace string
color *color.Color
lastLog time.Time
output io.Writer
fields map[string]any
mutex *sync.Mutex
}
// New creates a new debugger instance
func New(namespace string) *Debugger {
return newDebugger(namespace)
}
// With clones the debugger instance and adds a key-value pair to its fields (json serializeable)
func (d *Debugger) With(key string, value any) *Debugger {
d.mutex.Lock()
defer d.mutex.Unlock()
n := *d
maps.Copy(n.fields, d.fields)
if key == "" {
key = "(empty)"
}
if value == nil {
value = nil
}
if _, err := json.Marshal(value); err != nil {
value = "(not serializable)"
}
n.fields[key] = value
return &n
}
// Extend creates a new debugger instance with an extended namespace
func (d *Debugger) Extend(namespace string) *Debugger {
d.mutex.Lock()
defer d.mutex.Unlock()
n := *d
n.namespace = d.namespace + ":" + namespace
return &n
}
// SetOutput sets the output writer for the debugger instance
func (d *Debugger) SetOutput(output io.Writer) {
d.mutex.Lock()
defer d.mutex.Unlock()
d.output = output
}
func newDebugger(namespace string) *Debugger {
return &Debugger{
namespace: namespace,
color: getRandomColor(namespace),
lastLog: time.Now(),
output: nil,
fields: make(map[string]any),
mutex: &sync.Mutex{}}
}