Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Handle empty contexts in log.FromContext #1141

Merged
merged 1 commit into from
Aug 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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"},
))
})
})

})