Skip to content

Commit

Permalink
Add context support
Browse files Browse the repository at this point in the history
  • Loading branch information
iand committed Oct 20, 2020
1 parent ff9374e commit b13267f
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions logr.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ limitations under the License.
// named values).
package logr

import (
"context"
)

// TODO: consider adding back in format strings if they're really needed
// TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects)
// TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats
Expand Down Expand Up @@ -180,3 +184,20 @@ type Logger interface {
// InfoLogger provides compatibility with code that relies on the v0.1.0 interface
// Deprecated: use Logger instead. This will be removed in a future release.
type InfoLogger = Logger

type contextKey struct{}

// FromContext returns a logr.Logger constructed from the context or returns a null logger
// if no no logger details are found in the context.
func FromContext(ctx context.Context) Logger {
if v, ok := ctx.Value(contextKey{}).(Logger); ok {
return v
}

return nullLogger{}
}

// NewContext returns a new context derived from ctx that embeds the logger.
func NewContext(ctx context.Context, l Logger) context.Context {
return context.WithValue(ctx, contextKey{}, l)
}

0 comments on commit b13267f

Please sign in to comment.