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