|
| 1 | +package slogmulti |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "log/slog" |
| 7 | +) |
| 8 | + |
| 9 | +// NewInlineHandler is a shortcut to a handler that implements all methods. |
| 10 | +func NewInlineHandler( |
| 11 | + enabledFunc func(ctx context.Context, groups []string, attrs []slog.Attr, level slog.Level) bool, |
| 12 | + handleFunc func(ctx context.Context, groups []string, attrs []slog.Attr, record slog.Record) error, |
| 13 | +) slog.Handler { |
| 14 | + return &InlineHandler{ |
| 15 | + groups: []string{}, |
| 16 | + attrs: []slog.Attr{}, |
| 17 | + enabledFunc: enabledFunc, |
| 18 | + handleFunc: handleFunc, |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +var _ slog.Handler = (*InlineHandler)(nil) |
| 23 | + |
| 24 | +type InlineHandler struct { |
| 25 | + groups []string |
| 26 | + attrs []slog.Attr |
| 27 | + enabledFunc func(ctx context.Context, groups []string, attrs []slog.Attr, level slog.Level) bool |
| 28 | + handleFunc func(ctx context.Context, groups []string, attrs []slog.Attr, record slog.Record) error |
| 29 | +} |
| 30 | + |
| 31 | +// Implements slog.Handler |
| 32 | +func (h *InlineHandler) Enabled(ctx context.Context, level slog.Level) bool { |
| 33 | + return h.enabledFunc(ctx, h.groups, h.attrs, level) |
| 34 | +} |
| 35 | + |
| 36 | +// Implements slog.Handler |
| 37 | +func (h *InlineHandler) Handle(ctx context.Context, record slog.Record) error { |
| 38 | + return h.handleFunc(ctx, h.groups, h.attrs, record) |
| 39 | +} |
| 40 | + |
| 41 | +// Implements slog.Handler |
| 42 | +func (h *InlineHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 43 | + newAttrs := []slog.Attr{} |
| 44 | + newAttrs = append(newAttrs, h.attrs...) |
| 45 | + newAttrs = append(newAttrs, attrs...) |
| 46 | + |
| 47 | + return &InlineHandler{ |
| 48 | + groups: h.groups, |
| 49 | + attrs: newAttrs, |
| 50 | + enabledFunc: h.enabledFunc, |
| 51 | + handleFunc: h.handleFunc, |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// Implements slog.Handler |
| 56 | +func (h *InlineHandler) WithGroup(name string) slog.Handler { |
| 57 | + // https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247 |
| 58 | + if name == "" { |
| 59 | + return h |
| 60 | + } |
| 61 | + |
| 62 | + newGroups := []string{} |
| 63 | + newGroups = append(newGroups, h.groups...) |
| 64 | + newGroups = append(newGroups, name) |
| 65 | + return &InlineHandler{ |
| 66 | + groups: newGroups, |
| 67 | + attrs: h.attrs, |
| 68 | + enabledFunc: h.enabledFunc, |
| 69 | + handleFunc: h.handleFunc, |
| 70 | + } |
| 71 | +} |
0 commit comments