diff --git a/staging/src/k8s.io/component-base/logs/api/v1/options.go b/staging/src/k8s.io/component-base/logs/api/v1/options.go index 4abcc1de8129e..754443bf6fdc4 100644 --- a/staging/src/k8s.io/component-base/logs/api/v1/options.go +++ b/staging/src/k8s.io/component-base/logs/api/v1/options.go @@ -282,6 +282,7 @@ func apply(c *LoggingConfiguration, options *LoggingOptions, featureGate feature if err := loggingFlags.Lookup("vmodule").Value.Set(VModuleConfigurationPflag(&c.VModule).String()); err != nil { return fmt.Errorf("internal error while setting klog vmodule: %v", err) } + setSlogDefaultLogger() klog.StartFlushDaemon(c.FlushFrequency.Duration.Duration) klog.EnableContextualLogging(p.ContextualLoggingEnabled) return nil diff --git a/staging/src/k8s.io/component-base/logs/api/v1/options_no_slog.go b/staging/src/k8s.io/component-base/logs/api/v1/options_no_slog.go new file mode 100644 index 0000000000000..816948e0a6f56 --- /dev/null +++ b/staging/src/k8s.io/component-base/logs/api/v1/options_no_slog.go @@ -0,0 +1,24 @@ +//go:build !go1.21 +// +build !go1.21 + +/* +Copyright 2023 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 v1 + +func setSlogDefaultLogger() { + // Do nothing when build with Go < 1.21. +} diff --git a/staging/src/k8s.io/component-base/logs/api/v1/options_slog.go b/staging/src/k8s.io/component-base/logs/api/v1/options_slog.go new file mode 100644 index 0000000000000..31765e644db6a --- /dev/null +++ b/staging/src/k8s.io/component-base/logs/api/v1/options_slog.go @@ -0,0 +1,37 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 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 v1 + +import ( + "log/slog" + + "github.com/go-logr/logr" + "k8s.io/klog/v2" +) + +// setSlogDefaultLogger sets the global slog default logger to the same default +// that klog currently uses. +func setSlogDefaultLogger() { + // klog.Background() always returns a valid logr.Logger, regardless of + // how logging was configured. We just need to turn it into a + // slog.Handler. SetDefault then needs a slog.Logger. + handler := logr.ToSlogHandler(klog.Background()) + slog.SetDefault(slog.New(handler)) +} diff --git a/staging/src/k8s.io/component-base/logs/example/README.md b/staging/src/k8s.io/component-base/logs/example/README.md index a2a3a2951151c..aafc34d5036d7 100644 --- a/staging/src/k8s.io/component-base/logs/example/README.md +++ b/staging/src/k8s.io/component-base/logs/example/README.md @@ -5,6 +5,9 @@ component-base/logs and what effect the different command line options have. Like most Kubernetes components, `cmd` uses Cobra and pflags. `stdlib` uses just plain Go libraries. `test` contains a unit test with per-test output. +`slog2k8s` shows how an application using `log/slog` from Go 1.21 can include +packages from Kubernetes. `k8s2slog` is the other direction. + Below we can see examples of how some features work. ## Default diff --git a/staging/src/k8s.io/component-base/logs/example/k8s2slog/k8s2slog.go b/staging/src/k8s.io/component-base/logs/example/k8s2slog/k8s2slog.go new file mode 100644 index 0000000000000..c39ef9fe7a60f --- /dev/null +++ b/staging/src/k8s.io/component-base/logs/example/k8s2slog/k8s2slog.go @@ -0,0 +1,89 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2018 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 main + +import ( + "context" + "fmt" + "log/slog" + "os" + "strings" + + "github.com/spf13/cobra" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/component-base/cli" + "k8s.io/component-base/featuregate" + "k8s.io/component-base/logs" + logsapi "k8s.io/component-base/logs/api/v1" + "k8s.io/klog/v2" + + _ "k8s.io/component-base/logs/json/register" +) + +var featureGate = featuregate.NewFeatureGate() + +func main() { + runtime.Must(logsapi.AddFeatureGates(featureGate)) + command := NewLoggerCommand() + code := cli.Run(command) + os.Exit(code) +} + +func NewLoggerCommand() *cobra.Command { + c := logsapi.NewLoggingConfiguration() + cmd := &cobra.Command{ + Run: func(cmd *cobra.Command, args []string) { + // This configures the global logger in klog *and* slog, if compiled + // with Go >= 1.21. + logs.InitLogs() + if err := logsapi.ValidateAndApply(c, featureGate); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + if len(args) > 0 { + fmt.Fprintf(os.Stderr, "Unexpected additional command line arguments:\n %s\n", strings.Join(args, "\n ")) + os.Exit(1) + } + + // Produce some output. Special types used by Kubernetes work. + podRef := klog.KObj(&metav1.ObjectMeta{Name: "some-pod", Namespace: "some-namespace"}) + podRefs := klog.KObjSlice([]interface{}{ + &metav1.ObjectMeta{Name: "some-pod", Namespace: "some-namespace"}, + nil, + &metav1.ObjectMeta{Name: "other-pod"}, + }) + slog.Info("slog.Info", "pod", podRef, "pods", podRefs) + klog.InfoS("klog.InfoS", "pod", podRef, "pods", podRefs) + klog.Background().Info("klog.Background+logr.Logger.Info") + klog.FromContext(context.Background()).Info("klog.FromContext+logr.Logger.Info") + slogLogger := slog.Default() + slogLogger.Info("slog.Default+slog.Logger.Info") + }, + } + if err := logsapi.AddFeatureGates(featureGate); err != nil { + // Shouldn't happen. + panic(err) + } + featureGate.AddFlag(cmd.Flags()) + logsapi.AddFlags(c, cmd.Flags()) + return cmd +} diff --git a/staging/src/k8s.io/component-base/logs/example/slog2k8s/slog2k8s.go b/staging/src/k8s.io/component-base/logs/example/slog2k8s/slog2k8s.go new file mode 100644 index 0000000000000..440141e090087 --- /dev/null +++ b/staging/src/k8s.io/component-base/logs/example/slog2k8s/slog2k8s.go @@ -0,0 +1,50 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2023 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. +*/ + +// slog2k8s demonstrates how an application using log/slog for logging +// can include Kubernetes packages. +package main + +import ( + "context" + "log/slog" + "os" + + "k8s.io/klog/v2" +) + +func main() { + options := slog.HandlerOptions{AddSource: true} + textHandler := slog.NewTextHandler(os.Stderr, &options) + textLogger := slog.New(textHandler) + + // Use text output as default logger. + slog.SetDefault(textLogger) + + // This also needs to be done through klog to ensure that all code + // using klog uses the text handler. klog.Background/TODO/FromContext + // will return a thin wrapper around the textHandler, so all that klog + // still does is manage the global default and retrieval from contexts. + klog.SetSlogLogger(textLogger) + + textLogger.Info("slog.Logger.Info") + klog.InfoS("klog.InfoS") + klog.Background().Info("klog.Background+logr.Logger.Info") + klog.FromContext(context.Background()).Info("klog.FromContext+logr.Logger.Info") +}