Skip to content

Commit

Permalink
Move context key to internal package
Browse files Browse the repository at this point in the history
  • Loading branch information
veqryn committed Nov 26, 2023
1 parent 718c72d commit 7487869
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
11 changes: 5 additions & 6 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ package slogcontext
import (
"context"
"log/slog"
)

// Logger key for context.valueCtx
type ctxKey struct{}
"github.com/veqryn/slog-context/internal"
)

// ToCtx returns a copy of ctx with the logger attached.
// The parent context will be unaffected.
Expand All @@ -16,7 +15,7 @@ func ToCtx(parent context.Context, logger *slog.Logger) context.Context {
if parent == nil {
parent = context.Background()
}
return context.WithValue(parent, ctxKey{}, logger)
return context.WithValue(parent, internal.CtxKey{}, internal.LoggerCtxVal{Logger: logger})
}

// Logger returns the slog.Logger associated with the ctx.
Expand All @@ -26,8 +25,8 @@ func Logger(ctx context.Context) *slog.Logger {
if ctx == nil {
return slog.Default()
}
if l, ok := ctx.Value(ctxKey{}).(*slog.Logger); ok && l != nil {
return l
if l, ok := ctx.Value(internal.CtxKey{}).(internal.LoggerCtxVal); ok && l.Logger != nil {
return l.Logger
}
return slog.Default()
}
13 changes: 13 additions & 0 deletions internal/ctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package internal

import "log/slog"

// CtxKey Logger key for context.valueCtx
type CtxKey struct{}

// LoggerCtxVal is just a bucket containing a *slog.Logger
// and potentially other logger interfaces for interoperability.
type LoggerCtxVal struct {
Logger *slog.Logger
IterOp any
}

0 comments on commit 7487869

Please sign in to comment.