Skip to content

Commit

Permalink
Merge pull request #1141 from charithe/fix/logging-ctx
Browse files Browse the repository at this point in the history
🐛 Handle empty contexts in log.FromContext
  • Loading branch information
k8s-ci-robot committed Aug 26, 2020
2 parents 7dfe893 + 3cfd8b6 commit ba987e4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
16 changes: 8 additions & 8 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ var Log = NewDelegatingLogger(NullLogger{})

// FromContext returns a logger with predefined values from a context.Context.
func FromContext(ctx context.Context, keysAndValues ...interface{}) logr.Logger {
var log logr.Logger
if ctx == nil {
log = Log
} else {
lv := ctx.Value(contextKey)
log = lv.(logr.Logger)
var log logr.Logger = Log

if ctx != nil {
if lv := ctx.Value(contextKey); lv != nil {
log = lv.(logr.Logger)
}
}
log.WithValues(keysAndValues...)
return log

return log.WithValues(keysAndValues...)
}

// IntoContext takes a context and sets the logger as one of its keys.
Expand Down
42 changes: 42 additions & 0 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package log

import (
"context"

"github.com/go-logr/logr"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
Expand Down Expand Up @@ -214,4 +216,44 @@ var _ = Describe("logging", func() {
))
})
})

Describe("logger from context", func() {
It("should return default logger when context is empty", func() {
gotLog := FromContext(context.Background())
Expect(gotLog).To(Not(BeNil()))
})

It("should return existing logger", func() {
root := &fakeLoggerRoot{}
baseLog := &fakeLogger{root: root}

wantLog := baseLog.WithName("my-logger")
ctx := IntoContext(context.Background(), wantLog)

gotLog := FromContext(ctx)
Expect(gotLog).To(Not(BeNil()))

gotLog.Info("test message")
Expect(root.messages).To(ConsistOf(
logInfo{name: []string{"my-logger"}, msg: "test message"},
))
})

It("should have added key-values", func() {
root := &fakeLoggerRoot{}
baseLog := &fakeLogger{root: root}

wantLog := baseLog.WithName("my-logger")
ctx := IntoContext(context.Background(), wantLog)

gotLog := FromContext(ctx, "tag1", "value1")
Expect(gotLog).To(Not(BeNil()))

gotLog.Info("test message")
Expect(root.messages).To(ConsistOf(
logInfo{name: []string{"my-logger"}, tags: []interface{}{"tag1", "value1"}, msg: "test message"},
))
})
})

})

0 comments on commit ba987e4

Please sign in to comment.