Files
kubernetes/test/e2e/framework/ginkgologger.go
Patrick Ohly 43539c855f e2e framework: unify logging, support skipping helpers
ginkgo.GinkgoHelper is a recent addition to ginkgo which allows functions to
mark themselves as helper. This then changes which callstack gets reported for
failures. It makes sense to support the same mechanism also for logging.

There's also no reason why framework.Logf should produce output that is in a
different format than klog log entries. Having time stamps formatted
differently makes it hard to read test output which uses a mixture of both.
Another user-visible advantage is that the error log entry from
framework.ExpectNoError now references the test source code.

With textlogger there is a simple replacement for klog that can be reconfigured
to let the caller handle stack unwinding. klog itself doesn't support that
and should be modified to support it (feature freeze).

Emitting printf-style output via that logger would work, but become less
readable because the message string would get quoted instead of printing it
verbatim as before. So instead, the traditional klog header gets reproduced
in the framework code. In this example, the first line is from klog, the second
from Logf:

    I0111 11:00:54.088957  332873 factory.go:193] Registered Plugin "containerd"
    ...
      I0111 11:00:54.987534 332873 util.go:506] >>> kubeConfig: /var/run/kubernetes/admin.kubeconfig

Indention is a bit different because the initial output is printed before
installing the logger which writes through ginkgo.GinkgoWriter.

One welcome side effect is that now "go vet" detects mismatched parameters for
framework.Logf because fmt.Sprintf is called without mangling the format
string. Some of the calls were incorrect.
2024-01-20 18:23:31 +01:00

101 lines
3.1 KiB
Go

/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package framework contains provider-independent helper code for
// building and running E2E tests with Ginkgo. The actual Ginkgo test
// suites gets assembled by combining this framework, the optional
// provider support code and specific tests via a separate .go file
// like Kubernetes' test/e2e.go.
package framework
import (
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
ginkgotypes "github.com/onsi/ginkgo/v2/types"
"k8s.io/klog/v2"
"k8s.io/klog/v2/textlogger"
_ "k8s.io/component-base/logs/testinit" // Ensure command line flags are registered.
)
var (
logConfig = textlogger.NewConfig(
textlogger.Output(ginkgo.GinkgoWriter),
textlogger.Backtrace(unwind),
)
ginkgoLogger = textlogger.NewLogger(logConfig)
TimeNow = time.Now // Can be stubbed out for testing.
Pid = os.Getpid() // Can be stubbed out for testing.
)
func init() {
// ktesting and testinit already registered the -v and -vmodule
// command line flags. To configure the textlogger instead, we
// need to swap out the flag.Value for those.
var fs flag.FlagSet
logConfig.AddFlags(&fs)
fs.VisitAll(func(loggerFlag *flag.Flag) {
klogFlag := flag.CommandLine.Lookup(loggerFlag.Name)
if klogFlag != nil {
klogFlag.Value = loggerFlag.Value
}
})
// Now install the textlogger as the klog default logger.
// Calls like klog.Info then will write to ginkgo.GingoWriter
// through the textlogger.
//
// However, stack unwinding is then still being done by klog and thus
// ignores ginkgo.GingkoHelper. Tests should use framework.Logf or
// structured, contextual logging.
writer, _ := ginkgoLogger.GetSink().(textlogger.KlogBufferWriter)
opts := []klog.LoggerOption{
klog.ContextualLogger(true),
klog.WriteKlogBuffer(writer.WriteKlogBuffer),
}
klog.SetLoggerWithOptions(ginkgoLogger, opts...)
}
func unwind(skip int) (string, int) {
location := ginkgotypes.NewCodeLocation(skip + 1)
return location.FileName, location.LineNumber
}
// log re-implements klog.Info: same header, but stack unwinding
// with support for ginkgo.GinkgoWriter and skipping stack levels.
func log(offset int, msg string) {
now := TimeNow()
file, line := unwind(offset + 1)
if file == "" {
file = "???"
line = 1
} else if slash := strings.LastIndex(file, "/"); slash >= 0 {
file = file[slash+1:]
}
_, month, day := now.Date()
hour, minute, second := now.Clock()
header := fmt.Sprintf("I%02d%02d %02d:%02d:%02d.%06d %d %s:%d]",
month, day, hour, minute, second, now.Nanosecond()/1000, Pid, file, line)
fmt.Fprintln(ginkgo.GinkgoWriter, header, msg)
}