Skip to content

Commit 33351c0

Browse files
authored
Merge pull request #341 from pohly/contextual-logging-state-fix
contextual logging: enable by default again
2 parents ea66a13 + c2d5a45 commit 33351c0

2 files changed

Lines changed: 61 additions & 1 deletion

File tree

klog.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,11 @@ type loggingT struct {
550550
vmap map[uintptr]Level
551551
}
552552

553-
var logging loggingT
553+
var logging = loggingT{
554+
settings: settings{
555+
contextualLoggingEnabled: true,
556+
},
557+
}
554558

555559
// setVState sets a consistent state for V logging.
556560
// l.mu is held.

ktesting/contextual_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Copyright 2019 The Kubernetes Authors.
3+
Copyright 2020 Intel Coporation.
4+
5+
SPDX-License-Identifier: Apache-2.0
6+
*/
7+
8+
package ktesting_test
9+
10+
import (
11+
"context"
12+
"testing"
13+
14+
"k8s.io/klog/v2"
15+
"k8s.io/klog/v2/ktesting"
16+
)
17+
18+
func TestContextual(t *testing.T) {
19+
logger, ctx := ktesting.NewTestContext(t)
20+
21+
doSomething(ctx)
22+
23+
// When contextual logging is disabled, the output goes to klog
24+
// instead of the testing logger.
25+
state := klog.CaptureState()
26+
defer state.Restore()
27+
klog.EnableContextualLogging(false)
28+
doSomething(ctx)
29+
30+
testingLogger, ok := logger.GetSink().(ktesting.Underlier)
31+
if !ok {
32+
t.Fatal("Should have had a ktesting LogSink!?")
33+
}
34+
35+
actual := testingLogger.GetBuffer().String()
36+
expected := `INFO hello world
37+
INFO foo: hello also from me
38+
`
39+
if actual != expected {
40+
t.Errorf("mismatch in captured output, expected:\n%s\ngot:\n%s\n", expected, actual)
41+
}
42+
}
43+
44+
func doSomething(ctx context.Context) {
45+
logger := klog.FromContext(ctx)
46+
logger.Info("hello world")
47+
48+
logger = logger.WithName("foo")
49+
ctx = klog.NewContext(ctx, logger)
50+
doSomeMore(ctx)
51+
}
52+
53+
func doSomeMore(ctx context.Context) {
54+
logger := klog.FromContext(ctx)
55+
logger.Info("hello also from me")
56+
}

0 commit comments

Comments
 (0)