-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite.go
More file actions
108 lines (90 loc) · 2.19 KB
/
write.go
File metadata and controls
108 lines (90 loc) · 2.19 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package debugo
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type asJSON struct {
Timestamp string `json:"timestamp,omitempty"`
Namespace string `json:"namespace"`
Fields map[string]any `json:"fields,omitempty"`
Message string `json:"message"`
ElapsedMs int64 `json:"elapsed_ms"`
}
// Debug logs a message if the debuggers namespace matches
func (d *Debugger) Debug(message ...any) *Debugger {
d.write(message...)
return d
}
// Debugf logs a formatted message if the debuggers namespace matches
func (d *Debugger) Debugf(format string, message ...any) *Debugger {
d.write(fmt.Sprintf(format, message...))
return d
}
func (d *Debugger) write(message ...any) {
d.mutex.Lock()
defer d.mutex.Unlock()
if !d.matchNamespace() {
return
}
msg := fmt.Sprint(message...)
if msg == "" {
return
}
if GetFormat() == JSON {
d.writeJSON(message...)
return
}
// Optional timestamp
var timestamp string
if t := GetTimestamp(); t != nil {
timestamp = time.Now().Format(t.Format)
}
// Build log parts
parts := []string{}
if timestamp != "" {
parts = append(parts, timestamp)
}
if GetUseColors() {
parts = append(parts, d.color.Sprintf("%s", d.namespace))
} else {
parts = append(parts, d.namespace)
}
// append fields as key=value
for key, value := range d.fields {
if value == nil {
value = ""
}
parts = append(parts, fmt.Sprintf("%s=%v", key, value))
}
parts = append(parts, msg)
parts = append(parts, fmt.Sprintf("+%s", prettyPrintDuration(d.elapsed())))
log := strings.Join(parts, " ") + "\n"
// Write to output
if d.output != nil {
_, _ = fmt.Fprint(d.output, log)
} else if o := GetOutput(); o != nil {
_, _ = fmt.Fprint(o, log)
}
}
func (d *Debugger) writeJSON(message ...any) {
entry := asJSON{
Namespace: d.namespace,
Message: fmt.Sprint(message...),
Fields: d.fields,
ElapsedMs: d.elapsed().Milliseconds(),
}
if t := GetTimestamp(); t != nil {
entry.Timestamp = time.Now().Format(t.Format)
}
data, err := json.Marshal(entry)
if err != nil {
return
}
if d.output != nil {
_, _ = d.output.Write(append(data, '\n'))
} else if o := GetOutput(); o != nil {
_, _ = o.Write(append(data, '\n'))
}
}