Skip to content

Commit

Permalink
Merge pull request #396 from pohly/slog-helper
Browse files Browse the repository at this point in the history
logr v1.4.1 + SetSlogLogger
  • Loading branch information
k8s-ci-robot authored Jan 10, 2024
2 parents 2086216 + e4deee8 commit 2d08296
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 26 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ jobs:
test:
strategy:
matrix:
go-version: [1.18, 1.19, 1.20, 1.21]
go-version: ["1.18", "1.19", "1.20", "1.21"]
platform: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.platform }}
steps:
Expand All @@ -27,7 +27,7 @@ jobs:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: 1.18
go-version: 1.21
- name: Add GOBIN to PATH
run: echo "PATH=$(go env GOPATH)/bin:$PATH" >>$GITHUB_ENV
- name: Install dependencies
Expand Down
31 changes: 31 additions & 0 deletions contextual_slog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//go:build go1.21
// +build go1.21

/*
Copyright 2021 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 klog

import (
"log/slog"

"github.com/go-logr/logr"
)

// SetSlogLogger reconfigures klog to log through the slog logger. The logger must not be nil.
func SetSlogLogger(logger *slog.Logger) {
SetLoggerWithOptions(logr.FromSlogHandler(logger.Handler()), ContextualLogger(true))
}
48 changes: 48 additions & 0 deletions contextual_slog_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//go:build go1.21
// +build go1.21

/*
Copyright 2021 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 klog_test

import (
"log/slog"
"os"

"k8s.io/klog/v2"
)

func ExampleSetSlogLogger() {
state := klog.CaptureState()
defer state.Restore()

handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
// Avoid non-deterministic output.
return slog.Attr{}
}
return a
},
})
logger := slog.New(handler)
klog.SetSlogLogger(logger)
klog.Info("hello world")

// Output:
// level=INFO msg="hello world"
}
2 changes: 1 addition & 1 deletion examples/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module k8s.io/klog/examples
go 1.13

require (
github.com/go-logr/logr v1.3.0
github.com/go-logr/logr v1.4.1
github.com/go-logr/zapr v1.2.3
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
go.uber.org/goleak v1.1.12
Expand Down
4 changes: 2 additions & 2 deletions examples/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/zapr v1.2.3 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A=
github.com/go-logr/zapr v1.2.3/go.mod h1:eIauM6P8qSvTw5o2ez6UEAfGjQKrxQTl5EoK+Qa2oG4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module k8s.io/klog/v2

go 1.13
go 1.18

require github.com/go-logr/logr v1.3.0
require github.com/go-logr/logr v1.4.1
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
10 changes: 5 additions & 5 deletions klogr_slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
"strconv"
"time"

"github.com/go-logr/logr/slogr"
"github.com/go-logr/logr"

"k8s.io/klog/v2/internal/buffer"
"k8s.io/klog/v2/internal/serialize"
Expand All @@ -35,7 +35,7 @@ import (

func (l *klogger) Handle(ctx context.Context, record slog.Record) error {
if logging.logger != nil {
if slogSink, ok := logging.logger.GetSink().(slogr.SlogSink); ok {
if slogSink, ok := logging.logger.GetSink().(logr.SlogSink); ok {
// Let that logger do the work.
return slogSink.Handle(ctx, record)
}
Expand Down Expand Up @@ -77,13 +77,13 @@ func slogOutput(file string, line int, now time.Time, err error, s severity.Seve
buffer.PutBuffer(b)
}

func (l *klogger) WithAttrs(attrs []slog.Attr) slogr.SlogSink {
func (l *klogger) WithAttrs(attrs []slog.Attr) logr.SlogSink {
clone := *l
clone.values = serialize.WithValues(l.values, sloghandler.Attrs2KVList(l.groups, attrs))
return &clone
}

func (l *klogger) WithGroup(name string) slogr.SlogSink {
func (l *klogger) WithGroup(name string) logr.SlogSink {
clone := *l
if clone.groups != "" {
clone.groups += "." + name
Expand All @@ -93,4 +93,4 @@ func (l *klogger) WithGroup(name string) slogr.SlogSink {
return &clone
}

var _ slogr.SlogSink = &klogger{}
var _ logr.SlogSink = &klogger{}
17 changes: 9 additions & 8 deletions klogr_slog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import (
"os"
"time"

"github.com/go-logr/logr/slogr"
"github.com/go-logr/logr"

"k8s.io/klog/v2"
internal "k8s.io/klog/v2/internal/buffer"
)
Expand Down Expand Up @@ -71,7 +72,7 @@ func ExampleBackground_Slog() {
internal.Pid = 123

logrLogger := klog.Background()
slogHandler := slogr.NewSlogHandler(logrLogger)
slogHandler := logr.ToSlogHandler(logrLogger)
slogLogger := slog.New(slogHandler)

// Note that -vmodule does not work when using the slog API because
Expand Down Expand Up @@ -107,10 +108,10 @@ func ExampleBackground_Slog() {
)

// Output:
// I1224 12:30:40.000000 123 klogr_slog_test.go:80] "A debug message"
// I1224 12:30:40.000000 123 klogr_slog_test.go:82] "An info message"
// W1224 12:30:40.000000 123 klogr_slog_test.go:83] "A warning"
// E1224 12:30:40.000000 123 klogr_slog_test.go:84] "An error" err="fake error"
// I1224 12:30:40.000000 123 klogr_slog_test.go:87] "Grouping" top.sub={"str":"abc","bool":true,"bottom":{"coordinates":{"X":-1,"Y":-2}}} top.duration="1s" top.pi=3.12 top.e=2.71 top.moreCoordinates={"X":100,"Y":200}
// I1224 12:30:40.000000 123 klogr_slog_test.go:103] "slog values" variables={"a":1,"b":2} duration="1s" coordinates={"X":100,"Y":200}
// I1224 12:30:40.000000 123 klogr_slog_test.go:81] "A debug message"
// I1224 12:30:40.000000 123 klogr_slog_test.go:83] "An info message"
// W1224 12:30:40.000000 123 klogr_slog_test.go:84] "A warning"
// E1224 12:30:40.000000 123 klogr_slog_test.go:85] "An error" err="fake error"
// I1224 12:30:40.000000 123 klogr_slog_test.go:88] "Grouping" top.sub={"str":"abc","bool":true,"bottom":{"coordinates":{"X":-1,"Y":-2}}} top.duration="1s" top.pi=3.12 top.e=2.71 top.moreCoordinates={"X":100,"Y":200}
// I1224 12:30:40.000000 123 klogr_slog_test.go:104] "slog values" variables={"a":1,"b":2} duration="1s" coordinates={"X":100,"Y":200}
}
8 changes: 4 additions & 4 deletions textlogger/textlogger_slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"context"
"log/slog"

"github.com/go-logr/logr/slogr"
"github.com/go-logr/logr"

"k8s.io/klog/v2/internal/serialize"
"k8s.io/klog/v2/internal/sloghandler"
Expand All @@ -33,13 +33,13 @@ func (l *tlogger) Handle(ctx context.Context, record slog.Record) error {
return sloghandler.Handle(ctx, record, l.groups, l.printWithInfos)
}

func (l *tlogger) WithAttrs(attrs []slog.Attr) slogr.SlogSink {
func (l *tlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink {
clone := *l
clone.values = serialize.WithValues(l.values, sloghandler.Attrs2KVList(l.groups, attrs))
return &clone
}

func (l *tlogger) WithGroup(name string) slogr.SlogSink {
func (l *tlogger) WithGroup(name string) logr.SlogSink {
clone := *l
if clone.groups != "" {
clone.groups += "." + name
Expand All @@ -49,4 +49,4 @@ func (l *tlogger) WithGroup(name string) slogr.SlogSink {
return &clone
}

var _ slogr.SlogSink = &tlogger{}
var _ logr.SlogSink = &tlogger{}

0 comments on commit 2d08296

Please sign in to comment.