]> Cypherpunks.ru repositories - gostls13.git/blob - src/log/slog/handler.go
slog: fix grammatical mistakes in docs
[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 when 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         // AddSource causes the handler to compute the source code position
131         // of the log statement and add a SourceKey attribute to the output.
132         AddSource bool
133
134         // Level reports the minimum record level that will be logged.
135         // The handler discards records with lower levels.
136         // If Level is nil, the handler assumes LevelInfo.
137         // The handler calls Level.Level for each record processed;
138         // to adjust the minimum level dynamically, use a LevelVar.
139         Level Leveler
140
141         // ReplaceAttr is called to rewrite each non-group attribute before it is logged.
142         // The attribute's value has been resolved (see [Value.Resolve]).
143         // If ReplaceAttr returns an Attr with Key == "", the attribute is discarded.
144         //
145         // The built-in attributes with keys "time", "level", "source", and "msg"
146         // are passed to this function, except that time is omitted
147         // if zero, and source is omitted if AddSource is false.
148         //
149         // The first argument is a list of currently open groups that contain the
150         // Attr. It must not be retained or modified. ReplaceAttr is never called
151         // for Group attributes, only their contents. For example, the attribute
152         // list
153         //
154         //     Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
155         //
156         // results in consecutive calls to ReplaceAttr with the following arguments:
157         //
158         //     nil, Int("a", 1)
159         //     []string{"g"}, Int("b", 2)
160         //     nil, Int("c", 3)
161         //
162         // ReplaceAttr can be used to change the default keys of the built-in
163         // attributes, convert types (for example, to replace a `time.Time` with the
164         // integer seconds since the Unix epoch), sanitize personal information, or
165         // remove attributes from the output.
166         ReplaceAttr func(groups []string, a Attr) Attr
167 }
168
169 // Keys for "built-in" attributes.
170 const (
171         // TimeKey is the key used by the built-in handlers for the time
172         // when the log method is called. The associated Value is a [time.Time].
173         TimeKey = "time"
174         // LevelKey is the key used by the built-in handlers for the level
175         // of the log call. The associated value is a [Level].
176         LevelKey = "level"
177         // MessageKey is the key used by the built-in handlers for the
178         // message of the log call. The associated value is a string.
179         MessageKey = "msg"
180         // SourceKey is the key used by the built-in handlers for the source file
181         // and line of the log call. The associated value is a string.
182         SourceKey = "source"
183 )
184
185 type commonHandler struct {
186         json              bool // true => output JSON; false => output text
187         opts              HandlerOptions
188         preformattedAttrs []byte
189         groupPrefix       string   // for text: prefix of groups opened in preformatting
190         groups            []string // all groups started from WithGroup
191         nOpenGroups       int      // the number of groups opened in preformattedAttrs
192         mu                sync.Mutex
193         w                 io.Writer
194 }
195
196 func (h *commonHandler) clone() *commonHandler {
197         // We can't use assignment because we can't copy the mutex.
198         return &commonHandler{
199                 json:              h.json,
200                 opts:              h.opts,
201                 preformattedAttrs: slices.Clip(h.preformattedAttrs),
202                 groupPrefix:       h.groupPrefix,
203                 groups:            slices.Clip(h.groups),
204                 nOpenGroups:       h.nOpenGroups,
205                 w:                 h.w,
206         }
207 }
208
209 // enabled reports whether l is greater than or equal to the
210 // minimum level.
211 func (h *commonHandler) enabled(l Level) bool {
212         minLevel := LevelInfo
213         if h.opts.Level != nil {
214                 minLevel = h.opts.Level.Level()
215         }
216         return l >= minLevel
217 }
218
219 func (h *commonHandler) withAttrs(as []Attr) *commonHandler {
220         h2 := h.clone()
221         // Pre-format the attributes as an optimization.
222         prefix := buffer.New()
223         defer prefix.Free()
224         prefix.WriteString(h.groupPrefix)
225         state := h2.newHandleState((*buffer.Buffer)(&h2.preformattedAttrs), false, "", prefix)
226         defer state.free()
227         if len(h2.preformattedAttrs) > 0 {
228                 state.sep = h.attrSep()
229         }
230         state.openGroups()
231         for _, a := range as {
232                 state.appendAttr(a)
233         }
234         // Remember the new prefix for later keys.
235         h2.groupPrefix = state.prefix.String()
236         // Remember how many opened groups are in preformattedAttrs,
237         // so we don't open them again when we handle a Record.
238         h2.nOpenGroups = len(h2.groups)
239         return h2
240 }
241
242 func (h *commonHandler) withGroup(name string) *commonHandler {
243         if name == "" {
244                 return h
245         }
246         h2 := h.clone()
247         h2.groups = append(h2.groups, name)
248         return h2
249 }
250
251 func (h *commonHandler) handle(r Record) error {
252         state := h.newHandleState(buffer.New(), true, "", nil)
253         defer state.free()
254         if h.json {
255                 state.buf.WriteByte('{')
256         }
257         // Built-in attributes. They are not in a group.
258         stateGroups := state.groups
259         state.groups = nil // So ReplaceAttrs sees no groups instead of the pre groups.
260         rep := h.opts.ReplaceAttr
261         // time
262         if !r.Time.IsZero() {
263                 key := TimeKey
264                 val := r.Time.Round(0) // strip monotonic to match Attr behavior
265                 if rep == nil {
266                         state.appendKey(key)
267                         state.appendTime(val)
268                 } else {
269                         state.appendAttr(Time(key, val))
270                 }
271         }
272         // level
273         key := LevelKey
274         val := r.Level
275         if rep == nil {
276                 state.appendKey(key)
277                 state.appendString(val.String())
278         } else {
279                 state.appendAttr(Any(key, val))
280         }
281         // source
282         if h.opts.AddSource {
283                 state.appendAttr(Any(SourceKey, r.source()))
284         }
285         key = MessageKey
286         msg := r.Message
287         if rep == nil {
288                 state.appendKey(key)
289                 state.appendString(msg)
290         } else {
291                 state.appendAttr(String(key, msg))
292         }
293         state.groups = stateGroups // Restore groups passed to ReplaceAttrs.
294         state.appendNonBuiltIns(r)
295         state.buf.WriteByte('\n')
296
297         h.mu.Lock()
298         defer h.mu.Unlock()
299         _, err := h.w.Write(*state.buf)
300         return err
301 }
302
303 func (s *handleState) appendNonBuiltIns(r Record) {
304         // preformatted Attrs
305         if len(s.h.preformattedAttrs) > 0 {
306                 s.buf.WriteString(s.sep)
307                 s.buf.Write(s.h.preformattedAttrs)
308                 s.sep = s.h.attrSep()
309         }
310         // Attrs in Record -- unlike the built-in ones, they are in groups started
311         // from WithGroup.
312         s.prefix = buffer.New()
313         defer s.prefix.Free()
314         s.prefix.WriteString(s.h.groupPrefix)
315         s.openGroups()
316         r.Attrs(func(a Attr) bool {
317                 s.appendAttr(a)
318                 return true
319         })
320         if s.h.json {
321                 // Close all open groups.
322                 for range s.h.groups {
323                         s.buf.WriteByte('}')
324                 }
325                 // Close the top-level object.
326                 s.buf.WriteByte('}')
327         }
328 }
329
330 // attrSep returns the separator between attributes.
331 func (h *commonHandler) attrSep() string {
332         if h.json {
333                 return ","
334         }
335         return " "
336 }
337
338 // handleState holds state for a single call to commonHandler.handle.
339 // The initial value of sep determines whether to emit a separator
340 // before the next key, after which it stays true.
341 type handleState struct {
342         h       *commonHandler
343         buf     *buffer.Buffer
344         freeBuf bool           // should buf be freed?
345         sep     string         // separator to write before next key
346         prefix  *buffer.Buffer // for text: key prefix
347         groups  *[]string      // pool-allocated slice of active groups, for ReplaceAttr
348 }
349
350 var groupPool = sync.Pool{New: func() any {
351         s := make([]string, 0, 10)
352         return &s
353 }}
354
355 func (h *commonHandler) newHandleState(buf *buffer.Buffer, freeBuf bool, sep string, prefix *buffer.Buffer) handleState {
356         s := handleState{
357                 h:       h,
358                 buf:     buf,
359                 freeBuf: freeBuf,
360                 sep:     sep,
361                 prefix:  prefix,
362         }
363         if h.opts.ReplaceAttr != nil {
364                 s.groups = groupPool.Get().(*[]string)
365                 *s.groups = append(*s.groups, h.groups[:h.nOpenGroups]...)
366         }
367         return s
368 }
369
370 func (s *handleState) free() {
371         if s.freeBuf {
372                 s.buf.Free()
373         }
374         if gs := s.groups; gs != nil {
375                 *gs = (*gs)[:0]
376                 groupPool.Put(gs)
377         }
378 }
379
380 func (s *handleState) openGroups() {
381         for _, n := range s.h.groups[s.h.nOpenGroups:] {
382                 s.openGroup(n)
383         }
384 }
385
386 // Separator for group names and keys.
387 const keyComponentSep = '.'
388
389 // openGroup starts a new group of attributes
390 // with the given name.
391 func (s *handleState) openGroup(name string) {
392         if s.h.json {
393                 s.appendKey(name)
394                 s.buf.WriteByte('{')
395                 s.sep = ""
396         } else {
397                 s.prefix.WriteString(name)
398                 s.prefix.WriteByte(keyComponentSep)
399         }
400         // Collect group names for ReplaceAttr.
401         if s.groups != nil {
402                 *s.groups = append(*s.groups, name)
403         }
404 }
405
406 // closeGroup ends the group with the given name.
407 func (s *handleState) closeGroup(name string) {
408         if s.h.json {
409                 s.buf.WriteByte('}')
410         } else {
411                 (*s.prefix) = (*s.prefix)[:len(*s.prefix)-len(name)-1 /* for keyComponentSep */]
412         }
413         s.sep = s.h.attrSep()
414         if s.groups != nil {
415                 *s.groups = (*s.groups)[:len(*s.groups)-1]
416         }
417 }
418
419 // appendAttr appends the Attr's key and value using app.
420 // It handles replacement and checking for an empty key.
421 // after replacement).
422 func (s *handleState) appendAttr(a Attr) {
423         if rep := s.h.opts.ReplaceAttr; rep != nil && a.Value.Kind() != KindGroup {
424                 var gs []string
425                 if s.groups != nil {
426                         gs = *s.groups
427                 }
428                 // Resolve before calling ReplaceAttr, so the user doesn't have to.
429                 a.Value = a.Value.Resolve()
430                 a = rep(gs, a)
431         }
432         a.Value = a.Value.Resolve()
433         // Elide empty Attrs.
434         if a.isEmpty() {
435                 return
436         }
437         // Special case: Source.
438         if v := a.Value; v.Kind() == KindAny {
439                 if src, ok := v.Any().(*Source); ok {
440                         if s.h.json {
441                                 a.Value = src.group()
442                         } else {
443                                 a.Value = StringValue(fmt.Sprintf("%s:%d", src.File, src.Line))
444                         }
445                 }
446         }
447         if a.Value.Kind() == KindGroup {
448                 attrs := a.Value.Group()
449                 // Output only non-empty groups.
450                 if len(attrs) > 0 {
451                         // Inline a group with an empty key.
452                         if a.Key != "" {
453                                 s.openGroup(a.Key)
454                         }
455                         for _, aa := range attrs {
456                                 s.appendAttr(aa)
457                         }
458                         if a.Key != "" {
459                                 s.closeGroup(a.Key)
460                         }
461                 }
462         } else {
463                 s.appendKey(a.Key)
464                 s.appendValue(a.Value)
465         }
466 }
467
468 func (s *handleState) appendError(err error) {
469         s.appendString(fmt.Sprintf("!ERROR:%v", err))
470 }
471
472 func (s *handleState) appendKey(key string) {
473         s.buf.WriteString(s.sep)
474         if s.prefix != nil {
475                 // TODO: optimize by avoiding allocation.
476                 s.appendString(string(*s.prefix) + key)
477         } else {
478                 s.appendString(key)
479         }
480         if s.h.json {
481                 s.buf.WriteByte(':')
482         } else {
483                 s.buf.WriteByte('=')
484         }
485         s.sep = s.h.attrSep()
486 }
487
488 func (s *handleState) appendString(str string) {
489         if s.h.json {
490                 s.buf.WriteByte('"')
491                 *s.buf = appendEscapedJSONString(*s.buf, str)
492                 s.buf.WriteByte('"')
493         } else {
494                 // text
495                 if needsQuoting(str) {
496                         *s.buf = strconv.AppendQuote(*s.buf, str)
497                 } else {
498                         s.buf.WriteString(str)
499                 }
500         }
501 }
502
503 func (s *handleState) appendValue(v Value) {
504         var err error
505         if s.h.json {
506                 err = appendJSONValue(s, v)
507         } else {
508                 err = appendTextValue(s, v)
509         }
510         if err != nil {
511                 s.appendError(err)
512         }
513 }
514
515 func (s *handleState) appendTime(t time.Time) {
516         if s.h.json {
517                 appendJSONTime(s, t)
518         } else {
519                 writeTimeRFC3339Millis(s.buf, t)
520         }
521 }
522
523 // This takes half the time of Time.AppendFormat.
524 func writeTimeRFC3339Millis(buf *buffer.Buffer, t time.Time) {
525         year, month, day := t.Date()
526         buf.WritePosIntWidth(year, 4)
527         buf.WriteByte('-')
528         buf.WritePosIntWidth(int(month), 2)
529         buf.WriteByte('-')
530         buf.WritePosIntWidth(day, 2)
531         buf.WriteByte('T')
532         hour, min, sec := t.Clock()
533         buf.WritePosIntWidth(hour, 2)
534         buf.WriteByte(':')
535         buf.WritePosIntWidth(min, 2)
536         buf.WriteByte(':')
537         buf.WritePosIntWidth(sec, 2)
538         ns := t.Nanosecond()
539         buf.WriteByte('.')
540         buf.WritePosIntWidth(ns/1e6, 3)
541         _, offsetSeconds := t.Zone()
542         if offsetSeconds == 0 {
543                 buf.WriteByte('Z')
544         } else {
545                 offsetMinutes := offsetSeconds / 60
546                 if offsetMinutes < 0 {
547                         buf.WriteByte('-')
548                         offsetMinutes = -offsetMinutes
549                 } else {
550                         buf.WriteByte('+')
551                 }
552                 buf.WritePosIntWidth(offsetMinutes/60, 2)
553                 buf.WriteByte(':')
554                 buf.WritePosIntWidth(offsetMinutes%60, 2)
555         }
556 }