Skip to content

Commit 5d1d2d5

Browse files
committed
add SetSlogLogger
This is syntactic sugar, but it's still useful because it hides logr from developers who only care about klog and slog.
1 parent 39afdba commit 5d1d2d5

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

contextual_slog.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//go:build go1.21
2+
// +build go1.21
3+
4+
/*
5+
Copyright 2021 The Kubernetes Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
*/
19+
20+
package klog
21+
22+
import (
23+
"log/slog"
24+
25+
"github.com/go-logr/logr"
26+
)
27+
28+
// SetSlogLogger reconfigures klog to log through the slog logger. The logger must not be nil.
29+
func SetSlogLogger(logger *slog.Logger) {
30+
SetLoggerWithOptions(logr.FromSlogHandler(logger.Handler()), ContextualLogger(true))
31+
}

contextual_slog_example_test.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//go:build go1.21
2+
// +build go1.21
3+
4+
/*
5+
Copyright 2021 The Kubernetes Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
*/
19+
20+
package klog_test
21+
22+
import (
23+
"log/slog"
24+
"os"
25+
26+
"k8s.io/klog/v2"
27+
)
28+
29+
func ExampleSetSlogLogger() {
30+
state := klog.CaptureState()
31+
defer state.Restore()
32+
33+
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
34+
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
35+
if a.Key == slog.TimeKey {
36+
// Avoid non-deterministic output.
37+
return slog.Attr{}
38+
}
39+
return a
40+
},
41+
})
42+
logger := slog.New(handler)
43+
klog.SetSlogLogger(logger)
44+
klog.Info("hello world")
45+
46+
// Output:
47+
// level=INFO msg="hello world"
48+
}

0 commit comments

Comments
 (0)