Skip to content

add DefaultContext for slog #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions slog/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package slog

type contextValKey int

const (
defaultContextValKey contextValKey = iota
)
12 changes: 12 additions & 0 deletions slog/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ func init() {
// Default returns the default Logger.
func Default() *Logger { return defaultLogger.Load().(*Logger) }

func DefaultOfContext(ctx context.Context) *Logger {
if v := ctx.Value(defaultContextValKey); v != nil {
return v.(*Logger)
} else {
return Default()
}
}

func NewContext(parent context.Context, l *Logger) context.Context {
return context.WithValue(parent, defaultContextValKey, l)
}

// SetDefault makes l the default Logger.
// After this call, output from the log package's default Logger
// (as with [log.Print], etc.) will be logged at LevelInfo using l's Handler.
Expand Down
10 changes: 10 additions & 0 deletions slog/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -574,3 +574,13 @@ func TestPanics(t *testing.T) {
logBuf.Reset()
}
}

func TestContext(t *testing.T) {
logger := With("traceid", "123456")
ctx := context.Background()
ctx = NewContext(ctx, logger)
gotLogger := DefaultContext(ctx)
if gotLogger != logger {
t.Errorf("Logger is not equal in context value")
}
}