Skip to content

Commit

Permalink
runtime/logger: add SetLogger helper
Browse files Browse the repository at this point in the history
This adds a new helper which simultaneously configures
controller-runtime and klog to make use of the same logger instance.

Signed-off-by: Hidde Beydals <hidde@hhh.computer>
  • Loading branch information
hiddeco committed Mar 7, 2023
1 parent ab91ddc commit 23a1ea8
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion runtime/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"github.com/go-logr/logr"
"github.com/spf13/pflag"
"go.uber.org/zap/zapcore"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)

Expand Down Expand Up @@ -70,7 +72,7 @@ var stackLevelStrings = map[string]zapcore.Level{
// flag.Parse()
//
// // Use the values during the initialisation of the logger
// ctrl.SetLogger(logger.NewLogger(logOptions))
// logger.SetLogger(logger.NewLogger(loggerOptions))
// }
type Options struct {
LogEncoding string
Expand Down Expand Up @@ -112,3 +114,10 @@ func NewLogger(opts Options) logr.Logger {

return zap.New(zap.UseFlagOptions(&zapOpts))
}

// SetLogger sets the logger for the controller-runtime and klog packages to the given logger.
// It is not thread-safe, and should be called as early as possible in the program's execution.
func SetLogger(logger logr.Logger) {
ctrl.SetLogger(logger)
klog.SetLoggerWithOptions(logger.WithName("runtime"), klog.ContextualLogger(true))
}

0 comments on commit 23a1ea8

Please sign in to comment.