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.
11 "log/slog/internal/buffer"
18 // A Handler handles log records produced by a Logger..
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.
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.
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
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.)
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),
59 Handle(context.Context, Record) error
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
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.
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.
75 // A Handler should treat WithGroup as starting a Group of Attrs that ends
76 // at the end of the log event. That is,
78 // logger.WithGroup("s").LogAttrs(level, msg, slog.Int("a", 1), slog.Int("b", 2))
82 // logger.LogAttrs(level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
84 // If the name is empty, WithGroup returns the receiver.
85 WithGroup(name string) Handler
88 type defaultHandler struct {
90 // internal.DefaultOutput, except for testing
91 output func(pc uintptr, data []byte) error
94 func newDefaultHandler(output func(uintptr, []byte) error) *defaultHandler {
95 return &defaultHandler{
96 ch: &commonHandler{json: false},
101 func (*defaultHandler) Enabled(_ context.Context, l Level) bool {
102 return l >= LevelInfo
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 {
110 buf.WriteString(r.Level.String())
112 buf.WriteString(r.Message)
113 state := h.ch.newHandleState(buf, true, " ", nil)
115 state.appendNonBuiltIns(r)
116 return h.output(r.PC, *buf)
119 func (h *defaultHandler) WithAttrs(as []Attr) Handler {
120 return &defaultHandler{h.ch.withAttrs(as), h.output}
123 func (h *defaultHandler) WithGroup(name string) Handler {
124 return &defaultHandler{h.ch.withGroup(name), h.output}
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
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.
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.
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.
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
156 // Int("a", 1), Group("g", Int("b", 2)), Int("c", 3)
158 // results in consecutive calls to ReplaceAttr with the following arguments:
161 // []string{"g"}, Int("b", 2)
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
171 // Keys for "built-in" attributes.
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].
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].
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.
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.
187 type commonHandler struct {
188 json bool // true => output JSON; false => output text
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
198 func (h *commonHandler) clone() *commonHandler {
199 // We can't use assignment because we can't copy the mutex.
200 return &commonHandler{
203 preformattedAttrs: slices.Clip(h.preformattedAttrs),
204 groupPrefix: h.groupPrefix,
205 groups: slices.Clip(h.groups),
206 nOpenGroups: h.nOpenGroups,
211 // enabled reports whether l is greater than or equal to the
213 func (h *commonHandler) enabled(l Level) bool {
214 minLevel := LevelInfo
215 if h.opts.Level != nil {
216 minLevel = h.opts.Level.Level()
221 func (h *commonHandler) withAttrs(as []Attr) *commonHandler {
223 // Pre-format the attributes as an optimization.
224 prefix := buffer.New()
226 prefix.WriteString(h.groupPrefix)
227 state := h2.newHandleState((*buffer.Buffer)(&h2.preformattedAttrs), false, "", prefix)
229 if len(h2.preformattedAttrs) > 0 {
230 state.sep = h.attrSep()
233 for _, a := range as {
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)
244 func (h *commonHandler) withGroup(name string) *commonHandler {
249 h2.groups = append(h2.groups, name)
253 func (h *commonHandler) handle(r Record) error {
254 state := h.newHandleState(buffer.New(), true, "", nil)
257 state.buf.WriteByte('{')
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
264 if !r.Time.IsZero() {
266 val := r.Time.Round(0) // strip monotonic to match Attr behavior
269 state.appendTime(val)
271 state.appendAttr(Time(key, val))
279 state.appendString(val.String())
281 state.appendAttr(Any(key, val))
284 if h.opts.AddSource {
286 if frame.File != "" {
290 state.appendSource(frame.File, frame.Line)
293 buf.WriteString(frame.File) // TODO: escape?
295 buf.WritePosInt(frame.Line)
298 state.appendAttr(String(key, s))
306 state.appendString(msg)
308 state.appendAttr(String(key, msg))
310 state.groups = stateGroups // Restore groups passed to ReplaceAttrs.
311 state.appendNonBuiltIns(r)
312 state.buf.WriteByte('\n')
316 _, err := h.w.Write(*state.buf)
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()
327 // Attrs in Record -- unlike the built-in ones, they are in groups started
329 s.prefix = buffer.New()
330 defer s.prefix.Free()
331 s.prefix.WriteString(s.h.groupPrefix)
333 r.Attrs(func(a Attr) bool {
338 // Close all open groups.
339 for range s.h.groups {
342 // Close the top-level object.
347 // attrSep returns the separator between attributes.
348 func (h *commonHandler) attrSep() string {
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 {
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
367 var groupPool = sync.Pool{New: func() any {
368 s := make([]string, 0, 10)
372 func (h *commonHandler) newHandleState(buf *buffer.Buffer, freeBuf bool, sep string, prefix *buffer.Buffer) handleState {
380 if h.opts.ReplaceAttr != nil {
381 s.groups = groupPool.Get().(*[]string)
382 *s.groups = append(*s.groups, h.groups[:h.nOpenGroups]...)
387 func (s *handleState) free() {
391 if gs := s.groups; gs != nil {
397 func (s *handleState) openGroups() {
398 for _, n := range s.h.groups[s.h.nOpenGroups:] {
403 // Separator for group names and keys.
404 const keyComponentSep = '.'
406 // openGroup starts a new group of attributes
407 // with the given name.
408 func (s *handleState) openGroup(name string) {
414 s.prefix.WriteString(name)
415 s.prefix.WriteByte(keyComponentSep)
417 // Collect group names for ReplaceAttr.
419 *s.groups = append(*s.groups, name)
424 // closeGroup ends the group with the given name.
425 func (s *handleState) closeGroup(name string) {
429 (*s.prefix) = (*s.prefix)[:len(*s.prefix)-len(name)-1 /* for keyComponentSep */]
431 s.sep = s.h.attrSep()
433 *s.groups = (*s.groups)[:len(*s.groups)-1]
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 {
446 // Resolve before calling ReplaceAttr, so the user doesn't have to.
447 a.Value = a.Value.Resolve()
450 a.Value = a.Value.Resolve()
451 // Elide empty Attrs.
455 if a.Value.Kind() == KindGroup {
456 attrs := a.Value.Group()
457 // Output only non-empty groups.
459 // Inline a group with an empty key.
463 for _, aa := range attrs {
472 s.appendValue(a.Value)
476 func (s *handleState) appendError(err error) {
477 s.appendString(fmt.Sprintf("!ERROR:%v", err))
480 func (s *handleState) appendKey(key string) {
481 s.buf.WriteString(s.sep)
483 // TODO: optimize by avoiding allocation.
484 s.appendString(string(*s.prefix) + key)
493 s.sep = s.h.attrSep()
496 func (s *handleState) appendSource(file string, line int) {
499 *s.buf = appendEscapedJSONString(*s.buf, file)
501 s.buf.WritePosInt(line)
505 if needsQuoting(file) {
506 s.appendString(file + ":" + strconv.Itoa(line))
508 // common case: no quoting needed.
511 s.buf.WritePosInt(line)
516 func (s *handleState) appendString(str string) {
519 *s.buf = appendEscapedJSONString(*s.buf, str)
523 if needsQuoting(str) {
524 *s.buf = strconv.AppendQuote(*s.buf, str)
526 s.buf.WriteString(str)
531 func (s *handleState) appendValue(v Value) {
534 err = appendJSONValue(s, v)
536 err = appendTextValue(s, v)
543 func (s *handleState) appendTime(t time.Time) {
547 writeTimeRFC3339Millis(s.buf, t)
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)
556 buf.WritePosIntWidth(int(month), 2)
558 buf.WritePosIntWidth(day, 2)
560 hour, min, sec := t.Clock()
561 buf.WritePosIntWidth(hour, 2)
563 buf.WritePosIntWidth(min, 2)
565 buf.WritePosIntWidth(sec, 2)
568 buf.WritePosIntWidth(ns/1e6, 3)
569 _, offsetSeconds := t.Zone()
570 if offsetSeconds == 0 {
573 offsetMinutes := offsetSeconds / 60
574 if offsetMinutes < 0 {
576 offsetMinutes = -offsetMinutes
580 buf.WritePosIntWidth(offsetMinutes/60, 2)
582 buf.WritePosIntWidth(offsetMinutes%60, 2)