src.dualinventive.com/go/lib/dilog/context.go

23 lines
587 B
Go

package dilog
import "context"
type contextKey int
var contextLoggerKey contextKey
// NewContext adds the logger to a context, returns a new context with the logger in it
func NewContext(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, contextLoggerKey, logger)
}
// FromContext returns the logger from a context (previously set with NewContext)
// when it has no logger the Discard-logger is returned
func FromContext(ctx context.Context) Logger {
val := ctx.Value(contextLoggerKey)
if val != nil {
return val.(Logger)
}
return Discard
}