Skip to content

Commit

Permalink
Accept a Logger instead of a LoggerProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
MrAlias committed Mar 14, 2024
1 parent 40b9b00 commit 39537f6
Showing 1 changed file with 8 additions and 39 deletions.
47 changes: 8 additions & 39 deletions bridges/sloghandler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import (
"context"
"fmt"
"log/slog"
"runtime"
"slices"
"strings"
"sync"

"go.opentelemetry.io/otel/log"
Expand Down Expand Up @@ -48,9 +46,9 @@ type Handler struct {
// Ensure forward compatibility by explicitly making this not comparable.
noCmp [0]func() //nolint: unused // This is indeed used.

attrs *kvBuffer
group *group
logFn func(context.Context, slog.Record) log.Logger
attrs *kvBuffer
group *group
logger log.Logger
}

// Compile-time check *Handler implements slog.Handler.
Expand All @@ -59,46 +57,17 @@ var _ slog.Handler = (*Handler)(nil)
// New returns a new [Handler] to be used as an [slog.Handler].
//
// If lp is nil, [noop.LoggerProvider] will be used as the default.
func New(lp log.LoggerProvider, options ...Option) *Handler {
if lp == nil {
func New(l log.Logger, _ ...Option) *Handler {
if l == nil {
// Do not panic.
lp = noop.NewLoggerProvider()
}

c := newConfig(options)

var logFn func(context.Context, slog.Record) log.Logger
if c.loggerFunc != nil {
logFn = func(ctx context.Context, r slog.Record) log.Logger {
name, opts := c.loggerFunc(ctx, r)
return lp.Logger(name, opts...)
}
} else {
logFn = defaultLogFn(lp)
}

return &Handler{logFn: logFn}
}

func defaultLogFn(lp log.LoggerProvider) func(context.Context, slog.Record) log.Logger {
return func(_ context.Context, r slog.Record) log.Logger {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
return lp.Logger(parsePkg(f.Function, "log/slog"))
}
}

func parsePkg(fName, fallback string) string {
pkg, _, found := strings.Cut(fName, ".")
if !found {
return fallback
l = noop.Logger{}
}
return pkg
return &Handler{logger: l}
}

// Handle handles the passed record.
func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
h.logFn(ctx, record).Emit(ctx, h.convertRecord(record))
h.logger.Emit(ctx, h.convertRecord(record))
return nil
}

Expand Down

0 comments on commit 39537f6

Please sign in to comment.