Skip to content

Commit

Permalink
Merge pull request #341 from pohly/contextual-logging-state-fix
Browse files Browse the repository at this point in the history
contextual logging: enable by default again
  • Loading branch information
k8s-ci-robot committed Jul 7, 2022
2 parents ea66a13 + c2d5a45 commit 33351c0
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
6 changes: 5 additions & 1 deletion klog.go
Expand Up @@ -550,7 +550,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")
}

0 comments on commit 33351c0

Please sign in to comment.