This logr implementation can be used in tests to ensure that output
is associated with the currently running test. Compared to using the
global klog instance in a standard Go test that has some advantages:
- Log messages are associated with the currently running test.
Tests can run in parallel without interleaving their output.
- Log output is only printed when a test fails, unless "go test -v"
is used.
- Because of that, the logger can print more log messages by default,
with 5 being used because that is recommended for debugging in
https://github.com/kubernetes/community/blob/fbc5ca53d6bfd8388b335f7d0198b67a14b99d91/contributors/devel/sig-instrumentation/logging.md?plain=1#L34-L36
That threshold can be changed via -testing.v after registering
that flag by importing k8s.io/klog/v2/ktesting/init.
The motivation for hosting this logger in klog is that it shares the formatting
code with klogr. Conceptually this is identical to go-logr/logr/testing, just
the output is different (klog text format vs. JSON).
$ go test -v ./testinglogger/example/
=== RUN TestKlog
example_test.go:69: INFO hello world
example_test.go:70: ERROR failed err="failed: some error"
example_test.go:71: INFO verbosity 1
example_test.go:72: INFO main/helper: with prefix
example_test.go:73: INFO key/value pairs int=1 float=2 pair="(1, 2)" kobj="kube-system/sally"
--- PASS: TestKlog (0.00s)
The corresponding output from go-logr/logr/testing would be:
=== RUN TestLogr
example_test.go:69: "ts"="2021-09-07 16:44:54.307551" "level"=0 "msg"="hello world"
example_test.go:70: "ts"="2021-09-07 16:44:54.307664" "msg"="failed" "error"="failed: some error"
example_test.go:71: "ts"="2021-09-07 16:44:54.307686" "level"=1 "msg"="verbosity 1"
example_test.go:72: main/helper: "ts"="2021-09-07 16:44:54.307703" "level"=0 "msg"="with prefix"
example_test.go:73: "ts"="2021-09-07 16:44:54.307733" "level"=0 "msg"="key/value pairs" "int"=1 "float"=2 "pair"={} "kobj"={"name":"sally","namespace":"kube-system"}
--- PASS: TestLogr (0.00s)