Debian Codegraph @

src/log/slog/multi_handler.go

raw
1 // Copyright 2025 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 "errors"
10 )
11
12 // NewMultiHandler creates a [MultiHandler] with the given Handlers.
13 func NewMultiHandler(handlers ...Handler) *MultiHandler {
14 h := make([]Handler, len(handlers))
15 copy(h, handlers)
16 return &MultiHandler{multi: h}
17 }
18
19 // MultiHandler is a [Handler] that invokes all the given Handlers.
20 // Its Enabled method reports whether any of the handlers' Enabled methods return true.
21 // Its Handle, WithAttrs and WithGroup methods call the corresponding method on each of the enabled handlers.
22 type MultiHandler struct {
23 multi []Handler
24 }
25
26 func (h *MultiHandler) Enabled(ctx context.Context, l Level) bool {
27 for i := range h.multi {
28 if h.multi[i].Enabled(ctx, l) {
29 return true
30 }
31 }
32 return false
33 }
34
35 func (h *MultiHandler) Handle(ctx context.Context, r Record) error {
36 var errs []error
37 for i := range h.multi {
38 if h.multi[i].Enabled(ctx, r.Level) {
39 if err := h.multi[i].Handle(ctx, r.Clone()); err != nil {
40 errs = append(errs, err)
41 }
42 }
43 }
44 return errors.Join(errs...)
45 }
46
47 func (h *MultiHandler) WithAttrs(attrs []Attr) Handler {
48 handlers := make([]Handler, 0, len(h.multi))
49 for i := range h.multi {
50 handlers = append(handlers, h.multi[i].WithAttrs(attrs))
51 }
52 return &MultiHandler{multi: handlers}
53 }
54
55 func (h *MultiHandler) WithGroup(name string) Handler {
56 handlers := make([]Handler, 0, len(h.multi))
57 for i := range h.multi {
58 handlers = append(handlers, h.multi[i].WithGroup(name))
59 }
60 return &MultiHandler{multi: handlers}
61 }