-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_console.go
More file actions
275 lines (246 loc) · 6.04 KB
/
handler_console.go
File metadata and controls
275 lines (246 loc) · 6.04 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
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
package logi
import (
"context"
"encoding/json"
"io"
"log/slog"
"slices"
"strings"
"sync"
"time"
)
// ConsoleHandler is a custom implementation of slog.Handler that writes logs to an io.Writer.
// It formats time and level at the front, followed by a separator, then the unquoted message.
// The remaining attributes are output in JSON format.
type ConsoleHandler struct {
w io.Writer
opts slog.HandlerOptions
attrs []slog.Attr
groups []string
mu *sync.Mutex
color bool
}
// NewConsoleHandler creates a ConsoleHandler that writes to w
// using the given options. If opts is nil, default options are used.
func NewConsoleHandler(w io.Writer, opts *slog.HandlerOptions, color bool) *ConsoleHandler {
if opts == nil {
opts = &slog.HandlerOptions{}
}
return &ConsoleHandler{
w: w,
opts: *opts,
attrs: []slog.Attr{},
groups: []string{},
mu: &sync.Mutex{},
color: color,
}
}
// Enabled checks if the handler processes records at the given level.
// If a record's level is lower, the handler will ignore it.
func (h *ConsoleHandler) Enabled(_ context.Context, level slog.Level) bool {
minLevel := slog.LevelInfo
if h.opts.Level != nil {
minLevel = h.opts.Level.Level()
}
return level >= minLevel
}
// WithAttrs returns a new ConsoleHandler whose attributes consist of
// h's attributes followed by attrs.
func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
h2 := h.clone()
h2.attrs = append(h2.attrs, attrs...)
return h2
}
// WithGroup returns a new ConsoleHandler with the given group.
func (h *ConsoleHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := h.clone()
h2.groups = append(h2.groups, name)
return h2
}
// clone creates a copy of the handler
func (h *ConsoleHandler) clone() *ConsoleHandler {
return &ConsoleHandler{
w: h.w,
opts: h.opts,
attrs: slices.Clone(h.attrs),
groups: slices.Clone(h.groups),
mu: h.mu, // share mutex
color: h.color,
}
}
// Handle processes the record and formats the output
func (h *ConsoleHandler) Handle(ctx context.Context, r slog.Record) error {
// Build log output buffer
var buf strings.Builder
// Apply ReplaceAttr function
rep := h.opts.ReplaceAttr
// Always output time first
if !r.Time.IsZero() {
key := "time"
val := r.Time.Round(0) // remove monotonic clock
if rep == nil {
buf.WriteByte('[')
buf.WriteString(val.Format(time.RFC3339Nano))
buf.WriteByte(']')
} else {
attr := rep(nil, slog.Attr{Key: key, Value: slog.TimeValue(val)})
if !isEmptyAttr(attr) {
buf.WriteByte('[')
switch attr.Value.Kind() {
case slog.KindTime:
buf.WriteString(attr.Value.Time().Format(time.RFC3339Nano))
case slog.KindString:
buf.WriteString(attr.Value.String())
default:
buf.WriteString(val.Format(time.RFC3339Nano))
}
buf.WriteByte(']')
}
}
}
buf.WriteByte(' ')
level := r.Level.String()
if rep != nil {
attr := rep(nil, slog.Attr{Key: "level", Value: slog.StringValue(level)})
if !isEmptyAttr(attr) {
level = attr.Value.String()
}
}
buf.WriteByte('[')
buf.WriteString(level)
buf.WriteByte(']')
// Separator and message
buf.WriteByte(' ')
msg := r.Message
if rep != nil {
attr := rep(nil, slog.Attr{Key: "msg", Value: slog.StringValue(msg)})
if !isEmptyAttr(attr) {
msg = attr.Value.String()
}
}
buf.WriteString(msg)
// Collect remaining attributes into a JSON object
attrs := make(map[string]any)
// Process preset attributes first
for _, a := range h.attrs {
if a.Key == "time" || a.Key == "level" || a.Key == "msg" {
continue
}
if rep != nil {
a = rep(h.groups, a)
}
if !isEmptyAttr(a) {
addAttrToMap(attrs, a, h.groups)
}
}
// Process attributes from the record
r.Attrs(func(a slog.Attr) bool {
if a.Key == "time" || a.Key == "level" || a.Key == "msg" {
return true
}
if rep != nil {
a = rep(h.groups, a)
}
if !isEmptyAttr(a) {
addAttrToMap(attrs, a, h.groups)
}
return true
})
// Only add JSON if there are attributes
if len(attrs) > 0 {
jsonData, err := json.Marshal(attrs)
if err == nil {
buf.WriteByte(' ')
buf.Write(jsonData)
}
}
buf.WriteByte('\n')
output := buf.String()
if h.color {
// Apply color based on log level
color := getLevelColor(r.Level)
output = color + output + colorReset
}
// Write to output
h.mu.Lock()
defer h.mu.Unlock()
_, err := io.WriteString(h.w, output)
return err
}
// addAttrToMap adds an attribute to the map, appropriately handling groups
func addAttrToMap(attrs map[string]any, a slog.Attr, groups []string) {
key := a.Key
val := attrValueToInterface(a.Value)
// If no groups, add directly
if len(groups) == 0 {
attrs[key] = val
return
}
// Handle group nesting
current := attrs
for i, g := range groups {
if i == len(groups)-1 {
// Last group
nextMap, ok := current[g]
if !ok {
nextMap = make(map[string]any)
current[g] = nextMap
}
if m, ok := nextMap.(map[string]any); ok {
m[key] = val
} else {
// Unexpected type, create new map
newMap := make(map[string]any)
newMap[key] = val
current[g] = newMap
}
} else {
// Intermediate group
nextMap, ok := current[g]
if !ok {
nextMap = make(map[string]any)
current[g] = nextMap
}
if m, ok := nextMap.(map[string]any); ok {
current = m
} else {
// Unexpected type, create new map
newMap := make(map[string]any)
current[g] = newMap
current = newMap
}
}
}
}
// attrValueToInterface converts a slog.Value to any
func attrValueToInterface(v slog.Value) any {
switch v.Kind() {
case slog.KindAny:
return v.Any()
case slog.KindBool:
return v.Bool()
case slog.KindDuration:
return v.Duration()
case slog.KindFloat64:
return v.Float64()
case slog.KindInt64:
return v.Int64()
case slog.KindString:
return v.String()
case slog.KindTime:
return v.Time()
case slog.KindUint64:
return v.Uint64()
case slog.KindGroup:
result := make(map[string]any)
for _, a := range v.Group() {
result[a.Key] = attrValueToInterface(a.Value)
}
return result
default:
return v.String()
}
}