File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -125,6 +125,11 @@ var (
125
125
// get any actual logging.
126
126
Log = log .Log
127
127
128
+ // LoggerFromContext returns a logger with predefined values from a context.Context.
129
+ //
130
+ // This is meant to be used with the context supplied in a struct that satisfies the Reconciler interface.
131
+ LoggerFromContext = log .FromContext
132
+
128
133
// SetLogger sets a concrete logging implementation for all deferred Loggers.
129
134
SetLogger = log .SetLogger
130
135
)
Original file line number Diff line number Diff line change @@ -34,9 +34,15 @@ limitations under the License.
34
34
package log
35
35
36
36
import (
37
+ "context"
38
+
37
39
"github.com/go-logr/logr"
38
40
)
39
41
42
+ var (
43
+ contextKey = & struct {}{}
44
+ )
45
+
40
46
// SetLogger sets a concrete logging implementation for all deferred Loggers.
41
47
func SetLogger (l logr.Logger ) {
42
48
Log .Fulfill (l )
@@ -46,3 +52,22 @@ func SetLogger(l logr.Logger) {
46
52
// to another logr.Logger. You *must* call SetLogger to
47
53
// get any actual logging.
48
54
var Log = NewDelegatingLogger (NullLogger {})
55
+
56
+ // FromContext returns a logger with predefined values from a context.Context.
57
+ func FromContext (ctx context.Context , keysAndValues ... interface {}) logr.Logger {
58
+ var log logr.Logger
59
+ if ctx == nil {
60
+ log = Log
61
+ } else {
62
+ lv := ctx .Value (contextKey )
63
+ log = lv .(logr.Logger )
64
+ }
65
+ log .WithValues (keysAndValues ... )
66
+ return log
67
+ }
68
+
69
+ // IntoContext takes a context and sets the logger as one of its keys.
70
+ // Use FromContext function to retrieve the logger.
71
+ func IntoContext (ctx context.Context , log logr.Logger ) context.Context {
72
+ return context .WithValue (ctx , contextKey , log )
73
+ }
You can’t perform that action at this time.
0 commit comments