Skip to content

Commit

Permalink
feat: export context key (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas authored Jul 25, 2023
1 parent fb99176 commit 280c4e3
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@ import "context"

// WithContext wraps the given logger in context.
func WithContext(ctx context.Context, logger *Logger) context.Context {
return context.WithValue(ctx, loggerContextKey, logger)
return context.WithValue(ctx, ContextKey, logger)
}

// FromContext returns the logger from the given context.
// This will return the default package logger if no logger
// found in context.
func FromContext(ctx context.Context) *Logger {
if logger, ok := ctx.Value(loggerContextKey).(*Logger); ok {
if logger, ok := ctx.Value(ContextKey).(*Logger); ok {
return logger
}
return defaultLogger
}

type contextKey struct{}
type contextKey struct{ string }

var loggerContextKey = contextKey{}
// ContextKey is the key used to store the logger in context.
var ContextKey = contextKey{"log"}

0 comments on commit 280c4e3

Please sign in to comment.