Skip to content

Commit

Permalink
contextual logging: avoid extra SetContextualLogger API
Browse files Browse the repository at this point in the history
We can avoid the variant of SetLogger by indicating support via an additional
interface that the LogSink must implement. This was seen as a cleaner
approach (kubernetes#296 (comment)).
  • Loading branch information
pohly committed Mar 10, 2022
1 parent df761fd commit f6c3d15
Showing 1 changed file with 39 additions and 7 deletions.
46 changes: 39 additions & 7 deletions contextual.go
Expand Up @@ -65,22 +65,54 @@ var (
// To remove a backing logr implemention, use ClearLogger. Setting an
// empty logger with SetLogger(logr.Logger{}) does not work.
//
// If the logger instance implements the ContextualLogger interface in addition
// to logr.Logger, then the instance will also be called directly
// by code that retrieves a logger with FromContext, TODO, or Background.
// In that case the logger instance should do its own verbosity checks
// in Enabled because klog will not do that for it.
//
// AddSupportsContext can be used for loggers which don't know about this
// klog specific convention.
//
// Modifying the logger is not thread-safe and should be done while no other
// goroutines invoke log calls, usually during program initialization.
func SetLogger(logger logr.Logger) {
globalLogger = &logger
contextualLogger = false
if contextual, ok := logger.GetSink().(ContextualLogSink); ok && contextual.SupportsContext() {
contextualLogger = true
}
}

// SetContextualLogger does the same as SetLogger, but in addition the
// logger may also get called directly by code that retrieves it
// with FromContext, TODO or Background. The logger therefore must
// implements its own verbosity checking.
func SetContextualLogger(logger logr.Logger) {
globalLogger = &logger
contextualLogger = true
// ContextualLogSink is an extension of the logr.LogSink interface that
// indicates to SetLogger whether the logger may get called directly by
// application code. Only the LogSink seen by SetLogger needs to implement
// this, clones of it as they occur during logger.V, logger.WithName or
// logger.WithValues don't need it.
type ContextualLogSink interface {
logr.LogSink

// SupportsContext returns true if the logger may get called directly
// by application code.
SupportsContext() bool
}

// AddSupportsContext wraps a logger that doesn't know about ContextualLogSink
// so that SetLogger knows that it can also be called directly.
func AddSupportsContext(logger logr.Logger) logr.Logger {
return logr.New(contextualLogSinkWrapper{logger.GetSink()})
}

type contextualLogSinkWrapper struct {
logr.LogSink
}

func (c contextualLogSinkWrapper) SupportsContext() bool {
return true
}

var _ ContextualLogSink = contextualLogSinkWrapper{}

// ClearLogger removes a backing Logger implementation if one was set earlier
// with SetLogger.
//
Expand Down

0 comments on commit f6c3d15

Please sign in to comment.