Skip to content

Commit

Permalink
contextual logging: enable by default again
Browse files Browse the repository at this point in the history
Commit 3c90bf9 accidentally changed the
default for contextual logging from "enabled" to "disabled". The intention
always was and still is to make the new API do something useful by default and
only be more cautious in key Kubernetes binaries which have a feature gate.
  • Loading branch information
pohly committed Jul 6, 2022
1 parent 7a070b4 commit c2d5a45
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 @@ -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")
}

0 comments on commit c2d5a45

Please sign in to comment.