Skip to content

Commit

Permalink
AddStacktrace: Use slog.Level, rename to AddStacktraceAt
Browse files Browse the repository at this point in the history
Changes AddStacktrace to use a slog.Level instead of a Zap Level,
and renames it to AddStacktraceAt.
This leaves room for a LevelEnabler (as suggested in the PR)
to be specified with an AddStacktrace in the future.
  • Loading branch information
abhinav committed Aug 27, 2023
1 parent e63605e commit d5ebf65
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 10 deletions.
8 changes: 4 additions & 4 deletions exp/zapslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,16 @@ type Handler struct {
core zapcore.Core
name string // logger name
addCaller bool
addStack zapcore.LevelEnabler
addStackAt slog.Level
callerSkip int
}

// NewHandler builds a [Handler] that writes to the supplied [zapcore.Core]
// with options.
func NewHandler(core zapcore.Core, opts ...Option) *Handler {
h := &Handler{
core: core,
addStack: zapcore.ErrorLevel,
core: core,
addStackAt: slog.LevelError,
}
for _, v := range opts {
v.apply(h)
Expand Down Expand Up @@ -145,7 +145,7 @@ func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
}
}

if h.addStack.Enabled(zapLevel) {
if record.Level >= h.addStackAt {
// Skipping 3:
// zapslog/handler log/slog.(*Logger).log
// slog/logger log/slog.(*Logger).log
Expand Down
2 changes: 1 addition & 1 deletion exp/zapslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestAddCaller(t *testing.T) {
func TestAddStack(t *testing.T) {
r := require.New(t)
fac, logs := observer.New(zapcore.DebugLevel)
sl := slog.New(NewHandler(fac, AddStacktrace(zapcore.DebugLevel)))
sl := slog.New(NewHandler(fac, AddStacktrace(slog.LevelDebug)))
sl.Info("msg")

r.Len(logs.AllUntimed(), 1, "Expected exactly one entry to be logged")
Expand Down
10 changes: 5 additions & 5 deletions exp/zapslog/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

package zapslog

import "go.uber.org/zap/zapcore"
import "log/slog"

// An Option configures a slog Handler.
type Option interface {
Expand Down Expand Up @@ -64,10 +64,10 @@ func WithCallerSkip(skip int) Option {
})
}

// AddStacktrace configures the Logger to record a stack trace for all messages at
// or above a given level.
func AddStacktrace(lvl zapcore.LevelEnabler) Option {
// AddStacktraceAt configures the Logger to record a stack trace
// for all messages at or above a given level.
func AddStacktraceAt(lvl slog.Level) Option {
return optionFunc(func(log *Handler) {
log.addStack = lvl
log.addStackAt = lvl
})
}

0 comments on commit d5ebf65

Please sign in to comment.