Skip to content

Commit

Permalink
testenv: Allow klog and glog to coexist
Browse files Browse the repository at this point in the history
This change allows test environments with glog to work with testenv.
The logger initialization is moved from init() to a separate function
that's called when a new testenv Environment is created. This allows a
user to set their custom logger to the controller-runtime logger before
creating testenv because the controller-runtime deferred logger can only
be set once.

Signed-off-by: Sunny <darkowlzz@protonmail.com>
  • Loading branch information
darkowlzz committed Sep 23, 2021
1 parent f2b114a commit 6089e4d
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions runtime/testenv/testenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ package testenv

import (
"context"
"flag"
"fmt"
"sync"
"time"
Expand Down Expand Up @@ -52,11 +53,20 @@ var (
env *envtest.Environment
)

func init() {
klog.InitFlags(nil)
func initLogger() {
// NOTE: Set the klog flags on a separate FlagSet to avoid conflicting with
// any flags set by the application code. For example, an application
// importing glog would conflict with the flags set by klog, resulting in
// redeclaration of the same flags.
// This is based on klog's coexist with glog example, refer:
// https://github.com/kubernetes/klog/blob/f8e668dbaa5f6f0e6a5c24ffd7667263840d79ae/examples/coexist_glog/coexist_glog.go
// To override this logger setup, a custom logger can be created and
// assigned to the controller-runtime logger explicitly before creating
// testenv Environment.
klogFlags := flag.NewFlagSet("klog", flag.ExitOnError)
klog.InitFlags(klogFlags)
logger := klogr.New()
log.SetLogger(logger)
ctrl.SetLogger(logger)
}

var (
Expand Down Expand Up @@ -118,7 +128,31 @@ func WithCRDPath(path ...string) Option {
//
// NOTE: This function should be called only once for each package you are running tests within, usually the environment
// is initialised in a suite_test.go or <package>_test.go file within a `TestMain` function.
//
// When a testenv Environment is created, it initializes the
// controller-runtime's deferred logger with a default logger based on klog. In
// order to override this behavior, the controller-runtime logger can be
// initialized before creating testenv Environment.
//
// import (
// "testing"
//
// "github.com/fluxcd/pkg/runtime/testenv"
// ctrl "sigs.k8s.io/controller-runtime"
// "sigs.k8s.io/controller-runtime/pkg/log/zap"
// }
//
// func TestMain(m *testing.M) {
// zlog := zap.New(zap.UseDevMode(true))
// ctrl.SetLogger(zlog)
//
// testEnv = testenv.New()
// ...
// }
//
func New(o ...Option) *Environment {
initLogger()

opts := options{}
for _, apply := range o {
apply(&opts)
Expand Down

0 comments on commit 6089e4d

Please sign in to comment.