]> Cypherpunks.ru repositories - gostls13.git/blob - src/log/slog/handler.go
aa76fab514fc8cfdec5638be6a9003c35dba40d7
[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         "slices"
13         "strconv"
14         "sync"
15         "time"
16 )
17
18 // A Handler handles log records produced by a Logger..
19 //
20 // A typical handler may print log records to standard error,
21 // or write them to a file or database, or perhaps augment them
22 // with additional attributes and pass them on to another handler.
23 //
24 // Any of the Handler's methods may be called concurrently with itself
25 // or with other methods. It is the responsibility of the Handler to
26 // manage this concurrency.
27 //
28 // Users of the slog package should not invoke Handler methods directly.
29 // They should use the methods of [Logger] instead.
30 type Handler interface {
31         // Enabled reports whether the handler handles records at the given level.
32         // The handler ignores records whose level is lower.
33         // It is called early, before any arguments are processed,
34         // to save effort if the log event should be discarded.
35         // If called from a Logger method, the first argument is the context
36         // passed to that method, or context.Background() if nil was passed
37         // or the method does not take a context.
38         // The context is passed so Enabled can use its values
39         // to make a decision.
40         Enabled(context.Context, Level) bool
41
42         // Handle handles the Record.
43         // It will only be called Enabled returns true.
44         // The Context argument is as for Enabled.
45         // It is present solely to provide Handlers access to the context's values.
46         // Canceling the context should not affect record processing.
47         // (Among other things, log messages may be necessary to debug a
48         // cancellation-related problem.)
49         //
50         // Handle methods that produce output should observe the following rules:
51         //   - If r.Time is the zero time, ignore the time.
52         //   - If r.PC is zero, ignore it.
53         //   - Attr's values should be resolved.
54         //   - If an Attr's key and value are both the zero value, ignore the Attr.
55         //     This can be tested with attr.Equal(Attr{}).
56         //   - If a group's key is empty, inline the group's Attrs.
57         //   - If a group has no Attrs (even if it has a non-empty key),
58         //     ignore it.
59         Handle(context.Context, Record) error
60
61         // WithAttrs returns a new Handler whose attributes consist of
62         // both the receiver's attributes and the arguments.
63         // The Handler owns the slice: it may retain, modify or discard it.
64         WithAttrs(attrs []Attr) Handler
65
66         // WithGroup returns a new Handler with the given group appended to
67         // the receiver's existing groups.
68         // The keys of all subsequent attributes, whether added by With or in a
69         // Record, should be qualified by the sequence of group names.
70         //
71         // How this qualification happens is up to the Handler, so long as
72         // this Handler's attribute keys differ from those of another Handler
73         // with a different sequence of group names.
74         //
75         // A Handler should treat WithGroup as starting a Group of Attrs that ends
76         // at the end of the log event. That is,
77         //
78         //     logger.WithGroup("s").LogAttrs(level, msg, slog.Int("a", 1), slog.Int("b", 2))
79         //
80         // should behave like
81         //
82         //     logger.LogAttrs(level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
83         //
84         // If the name is empty, WithGroup returns the receiver.
85         WithGroup(name string) Handler
86 }
87
88 type defaultHandler struct {
89         ch *commonHandler
90         // internal.DefaultOutput, except for testing
91         output func(pc uintptr, data []byte) error
92 }
93
94 func newDefaultHandler(output func(uintptr, []byte) error) *defaultHandler {
95         return &defaultHandler{
96                 ch:     &commonHandler{json: false},
97                 output: output,
98         }
99 }
100
101 func (*defaultHandler) Enabled(_ context.Context, l Level) bool {
102         return l >= LevelInfo
103 }
104
105 // Collect the level, attributes and message in a string and
106 // write it with the default log.Logger.
107 // Let the log.Logger handle time and file/line.
108 func (h *defaultHandler) Handle(ctx context.Context, r Record) error {
109         buf := buffer.New()
110         buf.WriteString(r.Level.String())
111         buf.WriteByte(' ')
112         buf.WriteString(r.Message)
113         state := h.ch.newHandleState(buf, true, " ", nil)
114         defer state.free()
115         state.appendNonBuiltIns(r)
116         return h.output(r.PC, *buf)
117 }
118
119 func (h *defaultHandler) WithAttrs(as []Attr) Handler {
120         return &defaultHandler{h.ch.withAttrs(as), h.output}
121 }
122
123 func (h *defaultHandler) WithGroup(name string) Handler {
124         return &defaultHandler{h.ch.withGroup(name), h.output}
125 }
126
127 // HandlerOptions are options for a TextHandler or JSONHandler.
128 // A zero HandlerOptions consists entirely of default values.
129 type HandlerOptions struct {
130         // When AddSource is true, the handler adds a ("source", "file:line")
131         // attribute to the output indicating the source code position of the log
132         // statement. AddSource is false by default to skip the cost of computing
133         // this information.
134         AddSource bool
135
136         // Level reports the minimum record level that will be logged.
137         // The handler discards records with lower levels.
138         // If Level is nil, the handler assumes LevelInfo.
139         // The handler calls Level.Level for each record processed;
140         // to adjust the minimum level dynamically, use a LevelVar.
141         Level Leveler
142
143         // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
144         // The attribute's value has been resolved (see [Value.Resolve]).
145         // If ReplaceAttr returns an Attr with Key == "", the attribute is discarded.
146         //
147         // The built-in attributes with keys "time", "level", "source", and "msg"
148         // are passed to this function, except that time is omitted
149         // if zero, and source is omitted if AddSource is false.
150         //
151         // The first argument is a list of currently open groups that contain the
152         // Attr. It must not be retained or modified. ReplaceAttr is never called
153         // for Group attributes, only their contents. For example, the attribute
154         // list
155         //
156         //     Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
157         //
158         // results in consecutive calls to ReplaceAttr with the following arguments:
159         //
160         //     nil, Int("a", 1)
161         //     []string{"g"}, Int("b", 2)
162         //     nil, Int("c", 3)
163         //
164         // ReplaceAttr can be used to change the default keys of the built-in
165         // attributes, convert types (for example, to replace a `time.Time` with the
166         // integer seconds since the Unix epoch), sanitize personal information, or
167         // remove attributes from the output.
168         ReplaceAttr func(groups []string, a Attr) Attr
169 }
170
171 // Keys for "built-in" attributes.
172 const (
173         // TimeKey is the key used by the built-in handlers for the time
174         // when the log method is called. The associated Value is a [time.Time].
175         TimeKey = "time"
176         // LevelKey is the key used by the built-in handlers for the level
177         // of the log call. The associated value is a [Level].
178         LevelKey = "level"
179         // MessageKey is the key used by the built-in handlers for the
180         // message of the log call. The associated value is a string.
181         MessageKey = "msg"
182         // SourceKey is the key used by the built-in handlers for the source file
183         // and line of the log call. The associated value is a string.
184         SourceKey = "source"
185 )
186
187 type commonHandler struct {
188         json              bool // true => output JSON; false => output text
189         opts              HandlerOptions
190         preformattedAttrs []byte
191         groupPrefix       string   // for text: prefix of groups opened in preformatting
192         groups            []string // all groups started from WithGroup
193         nOpenGroups       int      // the number of groups opened in preformattedAttrs
194         mu                sync.Mutex
195         w                 io.Writer
196 }
197
198 func (h *commonHandler) clone() *commonHandler {
199         // We can't use assignment because we can't copy the mutex.
200         return &commonHandler{
201                 json:              h.json,
202                 opts:              h.opts,
203                 preformattedAttrs: slices.Clip(h.preformattedAttrs),
204                 groupPrefix:       h.groupPrefix,
205                 groups:            slices.Clip(h.groups),
206                 nOpenGroups:       h.nOpenGroups,
207                 w:                 h.w,
208         }
209 }
210
211 // enabled reports whether l is greater than or equal to the
212 // minimum level.
213 func (h *commonHandler) enabled(l Level) bool {
214         minLevel := LevelInfo
215         if h.opts.Level != nil {
216                 minLevel = h.opts.Level.Level()
217         }
218         return l >= minLevel
219 }
220
221 func (h *commonHandler) withAttrs(as []Attr) *commonHandler {
222         h2 := h.clone()
223         // Pre-format the attributes as an optimization.
224         prefix := buffer.New()
225         defer prefix.Free()
226         prefix.WriteString(h.groupPrefix)
227         state := h2.newHandleState((*buffer.Buffer)(&h2.preformattedAttrs), false, "", prefix)
228         defer state.free()
229         if len(h2.preformattedAttrs) > 0 {
230                 state.sep = h.attrSep()
231         }
232         state.openGroups()
233         for _, a := range as {
234                 state.appendAttr(a)
235         }
236         // Remember the new prefix for later keys.
237         h2.groupPrefix = state.prefix.String()
238         // Remember how many opened groups are in preformattedAttrs,
239         // so we don't open them again when we handle a Record.
240         h2.nOpenGroups = len(h2.groups)
241         return h2
242 }
243
244 func (h *commonHandler) withGroup(name string) *commonHandler {
245         if name == "" {
246                 return h
247         }
248         h2 := h.clone()
249         h2.groups = append(h2.groups, name)
250         return h2
251 }
252
253 func (h *commonHandler) handle(r Record) error {
254         state := h.newHandleState(buffer.New(), true, "", nil)
255         defer state.free()
256         if h.json {
257                 state.buf.WriteByte('{')
258         }
259         // Built-in attributes. They are not in a group.
260         stateGroups := state.groups
261         state.groups = nil // So ReplaceAttrs sees no groups instead of the pre groups.
262         rep := h.opts.ReplaceAttr
263         // time
264         if !r.Time.IsZero() {
265                 key := TimeKey
266                 val := r.Time.Round(0) // strip monotonic to match Attr behavior
267                 if rep == nil {
268                         state.appendKey(key)
269                         state.appendTime(val)
270                 } else {
271                         state.appendAttr(Time(key, val))
272                 }
273         }
274         // level
275         key := LevelKey
276         val := r.Level
277         if rep == nil {
278                 state.appendKey(key)
279                 state.appendString(val.String())
280         } else {
281                 state.appendAttr(Any(key, val))
282         }
283         // source
284         if h.opts.AddSource {
285                 frame := r.frame()
286                 if frame.File != "" {
287                         key := SourceKey
288                         if rep == nil {
289                                 state.appendKey(key)
290                                 state.appendSource(frame.File, frame.Line)
291                         } else {
292                                 buf := buffer.New()
293                                 buf.WriteString(frame.File) // TODO: escape?
294                                 buf.WriteByte(':')
295                                 buf.WritePosInt(frame.Line)
296                                 s := buf.String()
297                                 buf.Free()
298                                 state.appendAttr(String(key, s))
299                         }
300                 }
301         }
302         key = MessageKey
303         msg := r.Message
304         if rep == nil {
305                 state.appendKey(key)
306                 state.appendString(msg)
307         } else {
308                 state.appendAttr(String(key, msg))
309         }
310         state.groups = stateGroups // Restore groups passed to ReplaceAttrs.
311         state.appendNonBuiltIns(r)
312         state.buf.WriteByte('\n')
313
314         h.mu.Lock()
315         defer h.mu.Unlock()
316         _, err := h.w.Write(*state.buf)
317         return err
318 }
319
320 func (s *handleState) appendNonBuiltIns(r Record) {
321         // preformatted Attrs
322         if len(s.h.preformattedAttrs) > 0 {
323                 s.buf.WriteString(s.sep)
324                 s.buf.Write(s.h.preformattedAttrs)
325                 s.sep = s.h.attrSep()
326         }
327         // Attrs in Record -- unlike the built-in ones, they are in groups started
328         // from WithGroup.
329         s.prefix = buffer.New()
330         defer s.prefix.Free()
331         s.prefix.WriteString(s.h.groupPrefix)
332         s.openGroups()
333         r.Attrs(func(a Attr) bool {
334                 s.appendAttr(a)
335                 return true
336         })
337         if s.h.json {
338                 // Close all open groups.
339                 for range s.h.groups {
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, prefix *buffer.Buffer) handleState {
373         s := handleState{
374                 h:       h,
375                 buf:     buf,
376                 freeBuf: freeBuf,
377                 sep:     sep,
378                 prefix:  prefix,
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 }
396
397 func (s *handleState) openGroups() {
398         for _, n := range s.h.groups[s.h.nOpenGroups:] {
399                 s.openGroup(n)
400         }
401 }
402
403 // Separator for group names and keys.
404 const keyComponentSep = '.'
405
406 // openGroup starts a new group of attributes
407 // with the given name.
408 func (s *handleState) openGroup(name string) {
409         if s.h.json {
410                 s.appendKey(name)
411                 s.buf.WriteByte('{')
412                 s.sep = ""
413         } else {
414                 s.prefix.WriteString(name)
415                 s.prefix.WriteByte(keyComponentSep)
416         }
417         // Collect group names for ReplaceAttr.
418         if s.groups != nil {
419                 *s.groups = append(*s.groups, name)
420         }
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         if rep := s.h.opts.ReplaceAttr; rep != nil && a.Value.Kind() != KindGroup {
442                 var gs []string
443                 if s.groups != nil {
444                         gs = *s.groups
445                 }
446                 // Resolve before calling ReplaceAttr, so the user doesn't have to.
447                 a.Value = a.Value.Resolve()
448                 a = rep(gs, a)
449         }
450         a.Value = a.Value.Resolve()
451         // Elide empty Attrs.
452         if a.isEmpty() {
453                 return
454         }
455         if a.Value.Kind() == KindGroup {
456                 attrs := a.Value.Group()
457                 // Output only non-empty groups.
458                 if len(attrs) > 0 {
459                         // Inline a group with an empty key.
460                         if a.Key != "" {
461                                 s.openGroup(a.Key)
462                         }
463                         for _, aa := range attrs {
464                                 s.appendAttr(aa)
465                         }
466                         if a.Key != "" {
467                                 s.closeGroup(a.Key)
468                         }
469                 }
470         } else {
471                 s.appendKey(a.Key)
472                 s.appendValue(a.Value)
473         }
474 }
475
476 func (s *handleState) appendError(err error) {
477         s.appendString(fmt.Sprintf("!ERROR:%v", err))
478 }
479
480 func (s *handleState) appendKey(key string) {
481         s.buf.WriteString(s.sep)
482         if s.prefix != nil {
483                 // TODO: optimize by avoiding allocation.
484                 s.appendString(string(*s.prefix) + key)
485         } else {
486                 s.appendString(key)
487         }
488         if s.h.json {
489                 s.buf.WriteByte(':')
490         } else {
491                 s.buf.WriteByte('=')
492         }
493         s.sep = s.h.attrSep()
494 }
495
496 func (s *handleState) appendSource(file string, line int) {
497         if s.h.json {
498                 s.buf.WriteByte('"')
499                 *s.buf = appendEscapedJSONString(*s.buf, file)
500                 s.buf.WriteByte(':')
501                 s.buf.WritePosInt(line)
502                 s.buf.WriteByte('"')
503         } else {
504                 // text
505                 if needsQuoting(file) {
506                         s.appendString(file + ":" + strconv.Itoa(line))
507                 } else {
508                         // common case: no quoting needed.
509                         s.appendString(file)
510                         s.buf.WriteByte(':')
511                         s.buf.WritePosInt(line)
512                 }
513         }
514 }
515
516 func (s *handleState) appendString(str string) {
517         if s.h.json {
518                 s.buf.WriteByte('"')
519                 *s.buf = appendEscapedJSONString(*s.buf, str)
520                 s.buf.WriteByte('"')
521         } else {
522                 // text
523                 if needsQuoting(str) {
524                         *s.buf = strconv.AppendQuote(*s.buf, str)
525                 } else {
526                         s.buf.WriteString(str)
527                 }
528         }
529 }
530
531 func (s *handleState) appendValue(v Value) {
532         var err error
533         if s.h.json {
534                 err = appendJSONValue(s, v)
535         } else {
536                 err = appendTextValue(s, v)
537         }
538         if err != nil {
539                 s.appendError(err)
540         }
541 }
542
543 func (s *handleState) appendTime(t time.Time) {
544         if s.h.json {
545                 appendJSONTime(s, t)
546         } else {
547                 writeTimeRFC3339Millis(s.buf, t)
548         }
549 }
550
551 // This takes half the time of Time.AppendFormat.
552 func writeTimeRFC3339Millis(buf *buffer.Buffer, t time.Time) {
553         year, month, day := t.Date()
554         buf.WritePosIntWidth(year, 4)
555         buf.WriteByte('-')
556         buf.WritePosIntWidth(int(month), 2)
557         buf.WriteByte('-')
558         buf.WritePosIntWidth(day, 2)
559         buf.WriteByte('T')
560         hour, min, sec := t.Clock()
561         buf.WritePosIntWidth(hour, 2)
562         buf.WriteByte(':')
563         buf.WritePosIntWidth(min, 2)
564         buf.WriteByte(':')
565         buf.WritePosIntWidth(sec, 2)
566         ns := t.Nanosecond()
567         buf.WriteByte('.')
568         buf.WritePosIntWidth(ns/1e6, 3)
569         _, offsetSeconds := t.Zone()
570         if offsetSeconds == 0 {
571                 buf.WriteByte('Z')
572         } else {
573                 offsetMinutes := offsetSeconds / 60
574                 if offsetMinutes < 0 {
575                         buf.WriteByte('-')
576                         offsetMinutes = -offsetMinutes
577                 } else {
578                         buf.WriteByte('+')
579                 }
580                 buf.WritePosIntWidth(offsetMinutes/60, 2)
581                 buf.WriteByte(':')
582                 buf.WritePosIntWidth(offsetMinutes%60, 2)
583         }
584 }