~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
66 lines · 1.4 KB Raw History
package logx

import (
	"context"
	"log/slog"
	"slices"
	"sync/atomic"
)

type teeSink struct {
	extra atomic.Pointer[slog.Handler]
}

type Tee struct {
	primary slog.Handler

	sink *teeSink

	steps []func(slog.Handler) slog.Handler
}

var _ slog.Handler = (*Tee)(nil)

func NewTee(primary slog.Handler) *Tee {
	return &Tee{primary: primary, sink: &teeSink{}}
}

func (t *Tee) Attach(extra slog.Handler) {
	t.sink.extra.Store(&extra)
}

func (t *Tee) Enabled(ctx context.Context, level slog.Level) bool {
	return t.primary.Enabled(ctx, level)
}

func (t *Tee) Handle(ctx context.Context, record slog.Record) error {
	err := t.primary.Handle(ctx, record)
	if p := t.sink.extra.Load(); p != nil {
		extra := *p
		for _, step := range t.steps {
			extra = step(extra)
		}
		if extra.Enabled(ctx, record.Level) {
			_ = extra.Handle(ctx, record.Clone())
		}
	}
	return err
}

func (t *Tee) with(primary slog.Handler, step func(slog.Handler) slog.Handler) *Tee {
	return &Tee{primary: primary, sink: t.sink, steps: append(slices.Clone(t.steps), step)}
}

func (t *Tee) WithAttrs(attrs []slog.Attr) slog.Handler {
	if len(attrs) == 0 {
		return t
	}
	return t.with(t.primary.WithAttrs(attrs), func(h slog.Handler) slog.Handler { return h.WithAttrs(attrs) })
}

func (t *Tee) WithGroup(name string) slog.Handler {
	if name == "" {
		return t
	}
	return t.with(t.primary.WithGroup(name), func(h slog.Handler) slog.Handler { return h.WithGroup(name) })
}