Skip to content

Commit

Permalink
dedicated type for contextKey{} (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
ktong authored Feb 20, 2024
1 parent 59d5fe0 commit f58a8f1
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions sampling/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ type Handler struct {
level slog.Level

bufferPool *sync.Pool
contextKey struct{}
}

type contextKey struct{}

// New creates a new Handler with the given Option(s).
func New(handler slog.Handler, sampler func(ctx context.Context) bool, opts ...Option) Handler {
if handler == nil {
Expand Down Expand Up @@ -76,7 +77,7 @@ func (h Handler) Enabled(ctx context.Context, level slog.Level) bool {

// If the log has not been sampled and there is no buffer in context,
// then it only logs while the level is greater than or equal to the handler level.
if ctx.Value(h.contextKey) == nil && !h.sampler(ctx) {
if ctx.Value(contextKey{}) == nil && !h.sampler(ctx) {
return level >= h.level
}

Expand All @@ -90,7 +91,7 @@ func (h Handler) Handle(ctx context.Context, record slog.Record) error {

// If there is buffer in context and the log has not been sampled,
// then the record is handled by the buffer.
if b, ok := ctx.Value(h.contextKey).(*buffer); ok {
if b, ok := ctx.Value(contextKey{}).(*buffer); ok {
if record.Level < h.level {
return b.buffer(ctx, h.handler, record)
}
Expand Down Expand Up @@ -123,7 +124,7 @@ func (h Handler) WithGroup(name string) slog.Handler {
// defer cancel()
func (h Handler) WithBuffer(ctx context.Context) (context.Context, func()) {
buf := h.bufferPool.Get().(*buffer) //nolint:forcetypeassert,errcheck
ctx = context.WithValue(ctx, h.contextKey, buf)
ctx = context.WithValue(ctx, contextKey{}, buf)

return ctx, func() {
buf.reset()
Expand Down

0 comments on commit f58a8f1

Please sign in to comment.