Debian Codegraph @

src/log/slog/handler.go

raw
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package slog
6
7 import (
8 "context"
9 "fmt"
10 "io"
11 "log/slog/internal/buffer"
12 "reflect"
13 "slices"
14 "strconv"
15 "sync"
16 "time"
17 )
18
19 // A Handler handles log records produced by a Logger.
20 //
21 // A typical handler may print log records to standard error,
22 // or write them to a file or database, or perhaps augment them
23 // with additional attributes and pass them on to another handler.
24 //
25 // Any of the Handler's methods may be called concurrently with itself
26 // or with other methods. It is the responsibility of the Handler to
27 // manage this concurrency.
28 //
29 // Users of the slog package should not invoke Handler methods directly.
30 // They should use the methods of [Logger] instead.
31 //
32 // Before implementing your own handler, consult https://go.dev/s/slog-handler-guide.
33 type Handler interface {
34 // Enabled reports whether the handler handles records at the given level.
35 // The handler ignores records whose level is lower.
36 // It is called early, before any arguments are processed,
37 // to save effort if the log event should be discarded.
38 // If called from a Logger method, the first argument is the context
39 // passed to that method, or context.Background() if nil was passed
40 // or the method does not take a context.
41 // The context is passed so Enabled can use its values
42 // to make a decision.
43 Enabled(context.Context, Level) bool
44
45 // Handle handles the Record.
46 // It will only be called when Enabled returns true.
47 // The Context argument is as for Enabled.
48 // It is present solely to provide Handlers access to the context's values.
49 // Canceling the context should not affect record processing.
50 // (Among other things, log messages may be necessary to debug a
51 // cancellation-related problem.)
52 //
53 // Handle methods that produce output should observe the following rules:
54 // - If r.Time is the zero time, ignore the time.
55 // - If r.PC is zero, ignore it.
56 // - Attr's values should be resolved.
57 // - If an Attr's key and value are both the zero value, ignore the Attr.
58 // This can be tested with attr.Equal(Attr{}).
59 // - If a group's key is empty, inline the group's Attrs.
60 // - If a group has no Attrs (even if it has a non-empty key),
61 // ignore it.
62 //
63 // [Logger] discards any errors from Handle. Wrap the Handle method to
64 // process any errors from Handlers.
65 Handle(context.Context, Record) error
66
67 // WithAttrs returns a new Handler whose attributes consist of
68 // both the receiver's attributes and the arguments.
69 // The Handler owns the slice: it may retain, modify or discard it.
70 WithAttrs(attrs []Attr) Handler
71
72 // WithGroup returns a new Handler with the given group appended to
73 // the receiver's existing groups.
74 // The keys of all subsequent attributes, whether added by With or in a
75 // Record, should be qualified by the sequence of group names.
76 //
77 // How this qualification happens is up to the Handler, so long as
78 // this Handler's attribute keys differ from those of another Handler
79 // with a different sequence of group names.
80 //
81 // A Handler should treat WithGroup as starting a Group of Attrs that ends
82 // at the end of the log event. That is,
83 //
84 // logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2))
85 //
86 // should behave like
87 //
88 // logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
89 //
90 // If the name is empty, WithGroup returns the receiver.
91 WithGroup(name string) Handler
92 }
93
94 type defaultHandler struct {
95 ch *commonHandler
96 // internal.DefaultOutput, except for testing
97 output func(pc uintptr, data []byte) error
98 }
99
100 func newDefaultHandler(output func(uintptr, []byte) error) *defaultHandler {
101 return &defaultHandler{
102 ch: &commonHandler{json: false},
103 output: output,
104 }
105 }
106
107 func (*defaultHandler) Enabled(_ context.Context, l Level) bool {
108 return l >= logLoggerLevel.Level()
109 }
110
111 // Collect the level, attributes and message in a string and
112 // write it with the default log.Logger.
113 // Let the log.Logger handle time and file/line.
114 func (h *defaultHandler) Handle(ctx context.Context, r Record) error {
115 buf := buffer.New()
116 buf.WriteString(r.Level.String())
117 buf.WriteByte(' ')
118 buf.WriteString(r.Message)
119 state := h.ch.newHandleState(buf, true, " ")
120 defer state.free()
121 state.appendNonBuiltIns(r)
122 return h.output(r.PC, *buf)
123 }
124
125 func (h *defaultHandler) WithAttrs(as []Attr) Handler {
126 return &defaultHandler{h.ch.withAttrs(as), h.output}
127 }
128
129 func (h *defaultHandler) WithGroup(name string) Handler {
130 return &defaultHandler{h.ch.withGroup(name), h.output}
131 }
132
133 // HandlerOptions are options for a [TextHandler] or [JSONHandler].
134 // A zero HandlerOptions consists entirely of default values.
135 type HandlerOptions struct {
136 // AddSource causes the handler to compute the source code position
137 // of the log statement and add a SourceKey attribute to the output.
138 AddSource bool
139
140 // Level reports the minimum record level that will be logged.
141 // The handler discards records with lower levels.
142 // If Level is nil, the handler assumes LevelInfo.
143 // The handler calls Level.Level for each record processed;
144 // to adjust the minimum level dynamically, use a LevelVar.
145 Level Leveler
146
147 // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
148 // The attribute's value has been resolved (see [Value.Resolve]).
149 // If ReplaceAttr returns a zero Attr, the attribute is discarded.
150 //
151 // The built-in attributes with keys "time", "level", "source", and "msg"
152 // are passed to this function, except that time is omitted
153 // if zero, and source is omitted if AddSource is false.
154 //
155 // The first argument is a list of currently open groups that contain the
156 // Attr. It must not be retained or modified. ReplaceAttr is never called
157 // for Group attributes, only their contents. For example, the attribute
158 // list
159 //
160 // Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
161 //
162 // results in consecutive calls to ReplaceAttr with the following arguments:
163 //
164 // nil, Int("a", 1)
165 // []string{"g"}, Int("b", 2)
166 // nil, Int("c", 3)
167 //
168 // ReplaceAttr can be used to change the default keys of the built-in
169 // attributes, convert types (for example, to replace a `time.Time` with the
170 // integer seconds since the Unix epoch), sanitize personal information, or
171 // remove attributes from the output.
172 ReplaceAttr func(groups []string, a Attr) Attr
173 }
174
175 // Keys for "built-in" attributes.
176 const (
177 // TimeKey is the key used by the built-in handlers for the time
178 // when the log method is called. The associated Value is a [time.Time].
179 TimeKey = "time"
180 // LevelKey is the key used by the built-in handlers for the level
181 // of the log call. The associated value is a [Level].
182 LevelKey = "level"
183 // MessageKey is the key used by the built-in handlers for the
184 // message of the log call. The associated value is a string.
185 MessageKey = "msg"
186 // SourceKey is the key used by the built-in handlers for the source file
187 // and line of the log call. The associated value is a *[Source].
188 SourceKey = "source"
189 )
190
191 type commonHandler struct {
192 json bool // true => output JSON; false => output text
193 opts HandlerOptions
194 preformattedAttrs []byte
195 // groupPrefix is for the text handler only.
196 // It holds the prefix for groups that were already pre-formatted.
197 // A group will appear here when a call to WithGroup is followed by
198 // a call to WithAttrs.
199 groupPrefix string
200 groups []string // all groups started from WithGroup
201 nOpenGroups int // the number of groups opened in preformattedAttrs
202 mu *sync.Mutex
203 w io.Writer
204 }
205
206 func (h *commonHandler) clone() *commonHandler {
207 // We can't use assignment because we can't copy the mutex.
208 return &commonHandler{
209 json: h.json,
210 opts: h.opts,
211 preformattedAttrs: slices.Clip(h.preformattedAttrs),
212 groupPrefix: h.groupPrefix,
213 groups: slices.Clip(h.groups),
214 nOpenGroups: h.nOpenGroups,
215 w: h.w,
216 mu: h.mu, // mutex shared among all clones of this handler
217 }
218 }
219
220 // enabled reports whether l is greater than or equal to the
221 // minimum level.
222 func (h *commonHandler) enabled(l Level) bool {
223 minLevel := LevelInfo
224 if h.opts.Level != nil {
225 minLevel = h.opts.Level.Level()
226 }
227 return l >= minLevel
228 }
229
230 func (h *commonHandler) withAttrs(as []Attr) *commonHandler {
231 // We are going to ignore empty groups, so if the entire slice consists of
232 // them, there is nothing to do.
233 if countEmptyGroups(as) == len(as) {
234 return h
235 }
236 h2 := h.clone()
237 // Pre-format the attributes as an optimization.
238 state := h2.newHandleState((*buffer.Buffer)(&h2.preformattedAttrs), false, "")
239 defer state.free()
240 state.prefix.WriteString(h.groupPrefix)
241 if pfa := h2.preformattedAttrs; len(pfa) > 0 {
242 state.sep = h.attrSep()
243 if h2.json && pfa[len(pfa)-1] == '{' {
244 state.sep = ""
245 }
246 }
247 // Remember the position in the buffer, in case all attrs are empty.
248 pos := state.buf.Len()
249 state.openGroups()
250 if !state.appendAttrs(as) {
251 state.buf.SetLen(pos)
252 } else {
253 // Remember the new prefix for later keys.
254 h2.groupPrefix = state.prefix.String()
255 // Remember how many opened groups are in preformattedAttrs,
256 // so we don't open them again when we handle a Record.
257 h2.nOpenGroups = len(h2.groups)
258 }
259 return h2
260 }
261
262 func (h *commonHandler) withGroup(name string) *commonHandler {
263 h2 := h.clone()
264 h2.groups = append(h2.groups, name)
265 return h2
266 }
267
268 // handle is the internal implementation of Handler.Handle
269 // used by TextHandler and JSONHandler.
270 func (h *commonHandler) handle(r Record) error {
271 state := h.newHandleState(buffer.New(), true, "")
272 defer state.free()
273 if h.json {
274 state.buf.WriteByte('{')
275 }
276 // Built-in attributes. They are not in a group.
277 stateGroups := state.groups
278 state.groups = nil // So ReplaceAttrs sees no groups instead of the pre groups.
279 rep := h.opts.ReplaceAttr
280 // time
281 if !r.Time.IsZero() {
282 key := TimeKey
283 val := r.Time.Round(0) // strip monotonic to match Attr behavior
284 if rep == nil {
285 state.appendKey(key)
286 state.appendTime(val)
287 } else {
288 state.appendAttr(Time(key, val))
289 }
290 }
291 // level
292 key := LevelKey
293 val := r.Level
294 if rep == nil {
295 state.appendKey(key)
296 state.appendString(val.String())
297 } else {
298 state.appendAttr(Any(key, val))
299 }
300 // source
301 if h.opts.AddSource {
302 src := r.Source()
303 if src == nil {
304 src = &Source{}
305 }
306 state.appendAttr(Any(SourceKey, src))
307 }
308 key = MessageKey
309 msg := r.Message
310 if rep == nil {
311 state.appendKey(key)
312 state.appendString(msg)
313 } else {
314 state.appendAttr(String(key, msg))
315 }
316 state.groups = stateGroups // Restore groups passed to ReplaceAttrs.
317 state.appendNonBuiltIns(r)
318 state.buf.WriteByte('\n')
319
320 h.mu.Lock()
321 defer h.mu.Unlock()
322 _, err := h.w.Write(*state.buf)
323 return err
324 }
325
326 func (s *handleState) appendNonBuiltIns(r Record) {
327 // preformatted Attrs
328 if pfa := s.h.preformattedAttrs; len(pfa) > 0 {
329 s.buf.WriteString(s.sep)
330 s.buf.Write(pfa)
331 s.sep = s.h.attrSep()
332 if s.h.json && pfa[len(pfa)-1] == '{' {
333 s.sep = ""
334 }
335 }
336 // Attrs in Record -- unlike the built-in ones, they are in groups started
337 // from WithGroup.
338 // If the record has no Attrs, don't output any groups.
339 nOpenGroups := s.h.nOpenGroups
340 if r.NumAttrs() > 0 {
341 s.prefix.WriteString(s.h.groupPrefix)
342 // The group may turn out to be empty even though it has attrs (for
343 // example, ReplaceAttr may delete all the attrs).
344 // So remember where we are in the buffer, to restore the position
345 // later if necessary.
346 pos := s.buf.Len()
347 s.openGroups()
348 nOpenGroups = len(s.h.groups)
349 empty := true
350 r.Attrs(func(a Attr) bool {
351 if s.appendAttr(a) {
352 empty = false
353 }
354 return true
355 })
356 if empty {
357 s.buf.SetLen(pos)
358 nOpenGroups = s.h.nOpenGroups
359 }
360 }
361 if s.h.json {
362 // Close all open groups.
363 for range s.h.groups[:nOpenGroups] {
364 s.buf.WriteByte('}')
365 }
366 // Close the top-level object.
367 s.buf.WriteByte('}')
368 }
369 }
370
371 // attrSep returns the separator between attributes.
372 func (h *commonHandler) attrSep() string {
373 if h.json {
374 return ","
375 }
376 return " "
377 }
378
379 // handleState holds state for a single call to commonHandler.handle.
380 // The initial value of sep determines whether to emit a separator
381 // before the next key, after which it stays true.
382 type handleState struct {
383 h *commonHandler
384 buf *buffer.Buffer
385 freeBuf bool // should buf be freed?
386 sep string // separator to write before next key
387 prefix *buffer.Buffer // for text: key prefix
388 groups *[]string // pool-allocated slice of active groups, for ReplaceAttr
389 }
390
391 var groupPool = sync.Pool{New: func() any {
392 s := make([]string, 0, 10)
393 return &s
394 }}
395
396 func (h *commonHandler) newHandleState(buf *buffer.Buffer, freeBuf bool, sep string) handleState {
397 s := handleState{
398 h: h,
399 buf: buf,
400 freeBuf: freeBuf,
401 sep: sep,
402 prefix: buffer.New(),
403 }
404 if h.opts.ReplaceAttr != nil {
405 s.groups = groupPool.Get().(*[]string)
406 *s.groups = append(*s.groups, h.groups[:h.nOpenGroups]...)
407 }
408 return s
409 }
410
411 func (s *handleState) free() {
412 if s.freeBuf {
413 s.buf.Free()
414 }
415 if gs := s.groups; gs != nil {
416 *gs = (*gs)[:0]
417 groupPool.Put(gs)
418 }
419 s.prefix.Free()
420 }
421
422 func (s *handleState) openGroups() {
423 for _, n := range s.h.groups[s.h.nOpenGroups:] {
424 s.openGroup(n)
425 }
426 }
427
428 // Separator for group names and keys.
429 const keyComponentSep = '.'
430
431 // openGroup starts a new group of attributes
432 // with the given name.
433 func (s *handleState) openGroup(name string) {
434 if s.h.json {
435 s.appendKey(name)
436 s.buf.WriteByte('{')
437 s.sep = ""
438 } else {
439 s.prefix.WriteString(name)
440 s.prefix.WriteByte(keyComponentSep)
441 }
442 // Collect group names for ReplaceAttr.
443 if s.groups != nil {
444 *s.groups = append(*s.groups, name)
445 }
446 }
447
448 // closeGroup ends the group with the given name.
449 func (s *handleState) closeGroup(name string) {
450 if s.h.json {
451 s.buf.WriteByte('}')
452 } else {
453 (*s.prefix) = (*s.prefix)[:len(*s.prefix)-len(name)-1 /* for keyComponentSep */]
454 }
455 s.sep = s.h.attrSep()
456 if s.groups != nil {
457 *s.groups = (*s.groups)[:len(*s.groups)-1]
458 }
459 }
460
461 // appendAttrs appends the slice of Attrs.
462 // It reports whether something was appended.
463 func (s *handleState) appendAttrs(as []Attr) bool {
464 nonEmpty := false
465 for _, a := range as {
466 if s.appendAttr(a) {
467 nonEmpty = true
468 }
469 }
470 return nonEmpty
471 }
472
473 // appendAttr appends the Attr's key and value.
474 // It handles replacement and checking for an empty key.
475 // It reports whether something was appended.
476 func (s *handleState) appendAttr(a Attr) bool {
477 a.Value = a.Value.Resolve()
478 if rep := s.h.opts.ReplaceAttr; rep != nil && a.Value.Kind() != KindGroup {
479 var gs []string
480 if s.groups != nil {
481 gs = *s.groups
482 }
483 // a.Value is resolved before calling ReplaceAttr, so the user doesn't have to.
484 a = rep(gs, a)
485 // The ReplaceAttr function may return an unresolved Attr.
486 a.Value = a.Value.Resolve()
487 }
488 // Elide empty Attrs.
489 if a.isEmpty() {
490 return false
491 }
492 // Special case: Source.
493 if v := a.Value; v.Kind() == KindAny {
494 if src, ok := v.Any().(*Source); ok {
495 if src.isEmpty() {
496 return false
497 }
498 if s.h.json {
499 a.Value = src.group()
500 } else {
501 a.Value = StringValue(fmt.Sprintf("%s:%d", src.File, src.Line))
502 }
503 }
504 }
505 if a.Value.Kind() == KindGroup {
506 attrs := a.Value.Group()
507 // Output only non-empty groups.
508 if len(attrs) > 0 {
509 // The group may turn out to be empty even though it has attrs (for
510 // example, ReplaceAttr may delete all the attrs).
511 // So remember where we are in the buffer, to restore the position
512 // later if necessary.
513 pos := s.buf.Len()
514 // Inline a group with an empty key.
515 if a.Key != "" {
516 s.openGroup(a.Key)
517 }
518 if !s.appendAttrs(attrs) {
519 s.buf.SetLen(pos)
520 return false
521 }
522 if a.Key != "" {
523 s.closeGroup(a.Key)
524 }
525 }
526 } else {
527 s.appendKey(a.Key)
528 s.appendValue(a.Value)
529 }
530 return true
531 }
532
533 func (s *handleState) appendError(err error) {
534 s.appendString(fmt.Sprintf("!ERROR:%v", err))
535 }
536
537 func (s *handleState) appendKey(key string) {
538 s.buf.WriteString(s.sep)
539 if s.prefix != nil && len(*s.prefix) > 0 {
540 s.appendTwoStrings(string(*s.prefix), key)
541 } else {
542 s.appendString(key)
543 }
544 if s.h.json {
545 s.buf.WriteByte(':')
546 } else {
547 s.buf.WriteByte('=')
548 }
549 s.sep = s.h.attrSep()
550 }
551
552 // appendTwoStrings implements appendString(prefix + key), but faster.
553 func (s *handleState) appendTwoStrings(x, y string) {
554 buf := *s.buf
555 switch {
556 case s.h.json:
557 buf.WriteByte('"')
558 buf = appendEscapedJSONString(buf, x)
559 buf = appendEscapedJSONString(buf, y)
560 buf.WriteByte('"')
561 case !needsQuoting(x) && !needsQuoting(y):
562 buf.WriteString(x)
563 buf.WriteString(y)
564 default:
565 buf = strconv.AppendQuote(buf, x+y)
566 }
567 *s.buf = buf
568 }
569
570 func (s *handleState) appendString(str string) {
571 if s.h.json {
572 s.buf.WriteByte('"')
573 *s.buf = appendEscapedJSONString(*s.buf, str)
574 s.buf.WriteByte('"')
575 } else {
576 // text
577 if needsQuoting(str) {
578 *s.buf = strconv.AppendQuote(*s.buf, str)
579 } else {
580 s.buf.WriteString(str)
581 }
582 }
583 }
584
585 func (s *handleState) appendValue(v Value) {
586 defer func() {
587 if r := recover(); r != nil {
588 // If it panics with a nil pointer, the most likely cases are
589 // an encoding.TextMarshaler or error fails to guard against nil,
590 // in which case "<nil>" seems to be the feasible choice.
591 //
592 // Adapted from the code in fmt/print.go.
593 if v := reflect.ValueOf(v.any); v.Kind() == reflect.Pointer && v.IsNil() {
594 s.appendString("<nil>")
595 return
596 }
597
598 // Otherwise just print the original panic message.
599 s.appendString(fmt.Sprintf("!PANIC: %v", r))
600 }
601 }()
602
603 var err error
604 if s.h.json {
605 err = appendJSONValue(s, v)
606 } else {
607 err = appendTextValue(s, v)
608 }
609 if err != nil {
610 s.appendError(err)
611 }
612 }
613
614 func (s *handleState) appendTime(t time.Time) {
615 if s.h.json {
616 appendJSONTime(s, t)
617 } else {
618 *s.buf = appendRFC3339Millis(*s.buf, t)
619 }
620 }
621
622 func appendRFC3339Millis(b []byte, t time.Time) []byte {
623 // Format according to time.RFC3339Nano since it is highly optimized,
624 // but truncate it to use millisecond resolution.
625 // Unfortunately, that format trims trailing 0s, so add 1/10 millisecond
626 // to guarantee that there are exactly 4 digits after the period.
627 const prefixLen = len("2006-01-02T15:04:05.000")
628 n := len(b)
629 t = t.Truncate(time.Millisecond).Add(time.Millisecond / 10)
630 b = t.AppendFormat(b, time.RFC3339Nano)
631 b = append(b[:n+prefixLen], b[n+prefixLen+1:]...) // drop the 4th digit
632 return b
633 }
634
635 // DiscardHandler discards all log output.
636 // DiscardHandler.Enabled returns false for all Levels.
637 var DiscardHandler Handler = discardHandler{}
638
639 type discardHandler struct{}
640
641 func (dh discardHandler) Enabled(context.Context, Level) bool { return false }
642 func (dh discardHandler) Handle(context.Context, Record) error { return nil }
643 func (dh discardHandler) WithAttrs(attrs []Attr) Handler { return dh }
644 func (dh discardHandler) WithGroup(name string) Handler { return dh }