You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.2 KiB
61 lines
1.2 KiB
2 months ago
|
package log
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"log/slog"
|
||
|
)
|
||
|
|
||
|
type MultiHandler struct {
|
||
|
handlers []slog.Handler
|
||
|
}
|
||
|
|
||
|
func NewMultiHandler(handlers ...slog.Handler) slog.Handler {
|
||
|
return &MultiHandler{handlers}
|
||
|
}
|
||
|
|
||
|
func (h *MultiHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||
|
for _, handler := range h.handlers {
|
||
|
if handler.Enabled(ctx, level) {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
func (h *MultiHandler) Handle(ctx context.Context, record slog.Record) error {
|
||
|
var errs []error
|
||
|
for _, handler := range h.handlers {
|
||
|
if handler.Enabled(ctx, record.Level) {
|
||
|
ex := handler.Handle(ctx, record)
|
||
|
if ex != nil {
|
||
|
errs = append(errs, ex)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if len(errs) > 0 {
|
||
|
return errors.Join(errs...)
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (h *MultiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||
|
handlers := make([]slog.Handler, len(h.handlers))
|
||
|
for i, handler := range h.handlers {
|
||
|
handlers[i] = handler.WithAttrs(attrs)
|
||
|
}
|
||
|
return &MultiHandler{
|
||
|
handlers: handlers,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (h *MultiHandler) WithGroup(name string) slog.Handler {
|
||
|
handlers := make([]slog.Handler, len(h.handlers))
|
||
|
for i, handler := range h.handlers {
|
||
|
handlers[i] = handler.WithGroup(name)
|
||
|
}
|
||
|
return &MultiHandler{
|
||
|
handlers: handlers,
|
||
|
}
|
||
|
}
|