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

contextual logging: enable by default again #341

Merged
merged 1 commit into from Jul 7, 2022
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
6 changes: 5 additions & 1 deletion klog.go
Expand Up @@ -549,7 +549,11 @@ type loggingT struct {
vmap map[uintptr]Level
}

var logging loggingT
var logging = loggingT{
settings: settings{
contextualLoggingEnabled: true,
},
}

// setVState sets a consistent state for V logging.
// l.mu is held.
Expand Down
56 changes: 56 additions & 0 deletions ktesting/contextual_test.go
@@ -0,0 +1,56 @@
/*
Copyright 2019 The Kubernetes Authors.
Copyright 2020 Intel Coporation.

SPDX-License-Identifier: Apache-2.0
*/

package ktesting_test

import (
"context"
"testing"

"k8s.io/klog/v2"
"k8s.io/klog/v2/ktesting"
)

func TestContextual(t *testing.T) {
logger, ctx := ktesting.NewTestContext(t)

doSomething(ctx)

// When contextual logging is disabled, the output goes to klog
// instead of the testing logger.
state := klog.CaptureState()
defer state.Restore()
klog.EnableContextualLogging(false)
doSomething(ctx)

testingLogger, ok := logger.GetSink().(ktesting.Underlier)
if !ok {
t.Fatal("Should have had a ktesting LogSink!?")
}

actual := testingLogger.GetBuffer().String()
expected := `INFO hello world
INFO foo: hello also from me
`
if actual != expected {
t.Errorf("mismatch in captured output, expected:\n%s\ngot:\n%s\n", expected, actual)
}
}

func doSomething(ctx context.Context) {
logger := klog.FromContext(ctx)
logger.Info("hello world")

logger = logger.WithName("foo")
ctx = klog.NewContext(ctx, logger)
doSomeMore(ctx)
}

func doSomeMore(ctx context.Context) {
logger := klog.FromContext(ctx)
logger.Info("hello also from me")
}