From c2d5a451f664994c87cfcf64e414d537a5892751 Mon Sep 17 00:00:00 2001 From: Patrick Ohly Date: Wed, 6 Jul 2022 14:33:03 +0200 Subject: [PATCH] contextual logging: enable by default again Commit 3c90bf9a79bf6ed7c82fa8cafeaf1681c8555255 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. --- klog.go | 6 +++- ktesting/contextual_test.go | 56 +++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 ktesting/contextual_test.go diff --git a/klog.go b/klog.go index 8305e252..00715b11 100644 --- a/klog.go +++ b/klog.go @@ -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. diff --git a/ktesting/contextual_test.go b/ktesting/contextual_test.go new file mode 100644 index 00000000..f260fb0a --- /dev/null +++ b/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") +}