-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
slogr: add glue code for logging to slog.Handler and with slog.Logger
Interoperability with log/slog from Go 1.21 includes the ability to use a slog.Handler as backend with logr.Logger as frontend and vice versa. This is only the initial step. In particular writing with slog.Logger to a logr.LogSink is not working well (time stamp and call site from record get ignored). Further work is needed to improve this.
- Loading branch information
Showing
6 changed files
with
384 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
//go:build go1.21 | ||
// +build go1.21 | ||
|
||
/* | ||
Copyright 2023 The logr 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 slogr | ||
|
||
import ( | ||
"context" | ||
"log/slog" | ||
|
||
"github.com/go-logr/logr" | ||
) | ||
|
||
type slogHandler struct { | ||
sink logr.LogSink | ||
groupPrefix string | ||
level slog.Level | ||
} | ||
|
||
var _ slog.Handler = &slogHandler{} | ||
|
||
// groupSeparator is used to concatenate WithGroup names and attribute keys. | ||
const groupSeparator = "." | ||
|
||
func (l *slogHandler) Enabled(ctx context.Context, level slog.Level) bool { | ||
return l.sink != nil && (level >= slog.LevelError || l.sink.Enabled(l.levelFromSlog(level))) | ||
} | ||
|
||
func (l *slogHandler) Handle(ctx context.Context, record slog.Record) error { | ||
// No need to check for nil sink here because Handle will only be called | ||
// when Enabled returned true. | ||
|
||
kvList := make([]any, 0, 2*record.NumAttrs()) | ||
record.Attrs(func(attr slog.Attr) bool { | ||
kvList = append(kvList, l.addGroupPrefix(attr.Key), attr.Value.Any()) | ||
return true | ||
}) | ||
if record.Level >= slog.LevelError { | ||
l.sink.Error(nil, record.Message, kvList...) | ||
} else { | ||
level := l.levelFromSlog(record.Level) | ||
l.sink.Info(level, record.Message, kvList...) | ||
} | ||
return nil | ||
} | ||
|
||
func (l slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { | ||
kvList := make([]any, 0, 2*len(attrs)) | ||
for _, attr := range attrs { | ||
kvList = append(kvList, l.addGroupPrefix(attr.Key), attr.Value.Any()) | ||
} | ||
l.sink = l.sink.WithValues(kvList...) | ||
return &l | ||
} | ||
|
||
func (l slogHandler) WithGroup(name string) slog.Handler { | ||
l.groupPrefix = l.addGroupPrefix(name) | ||
return &l | ||
} | ||
|
||
func (l *slogHandler) addGroupPrefix(name string) string { | ||
if l.groupPrefix == "" { | ||
return name | ||
} | ||
return l.groupPrefix + groupSeparator + name | ||
} | ||
|
||
func (l *slogHandler) levelFromSlog(level slog.Level) int { | ||
// Adjust by the per-logger verbosity level. | ||
level -= l.level | ||
if level >= 0 { | ||
// logr has no level lower than 0, so we have to truncate. | ||
// LogSink implementations might not expect a negative value. | ||
return 0 | ||
} | ||
return int(-level) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
//go:build go1.21 | ||
// +build go1.21 | ||
|
||
/* | ||
Copyright 2023 The logr 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 slogr | ||
|
||
import ( | ||
"log/slog" | ||
|
||
"github.com/go-logr/logr" | ||
) | ||
|
||
// New returns a logr.Logger which writes to the same handler as the slog.Logger. | ||
// | ||
// In the output the logr verbosity level gets negated, so V(4) becomes | ||
// slog.LevelDebug. | ||
func New(logger *slog.Logger) logr.Logger { | ||
return logr.New(&slogSink{handler: logger.Handler()}) | ||
} | ||
|
||
// NewSlogLogger returns a slog.Logger which writes to the same sink as the logr.Logger. | ||
// | ||
// The returned logger writes all records with level >= slog.LevelError as | ||
// error log entries with LogSink.Error, regardless of the verbosity of the | ||
// logr.Logger. The level of all other records gets reduced by the verbosity | ||
// level of the logr.Logger, so a slog.Logger.Info call gets written with | ||
// slog.LevelDebug when using a logr.Logger where verbosity was modified with | ||
// V(4). | ||
func NewSlogLogger(logger logr.Logger) *slog.Logger { | ||
return slog.New(&slogHandler{sink: logger.GetSink(), level: slog.Level(logger.GetV())}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
//go:build go1.21 | ||
// +build go1.21 | ||
|
||
/* | ||
Copyright 2023 The logr 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 slogr_test | ||
|
||
import ( | ||
"bytes" | ||
"errors" | ||
"fmt" | ||
"log/slog" | ||
"os" | ||
"path" | ||
"runtime" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/go-logr/logr" | ||
"github.com/go-logr/logr/funcr" | ||
"github.com/go-logr/logr/slogr" | ||
) | ||
|
||
var debugWithoutTime = &slog.HandlerOptions{ | ||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { | ||
if a.Key == "time" { | ||
return slog.Attr{} | ||
} | ||
return a | ||
}, | ||
Level: slog.LevelDebug, | ||
} | ||
|
||
func ExampleNew() { | ||
logger := slogr.New(slog.New(slog.NewTextHandler(os.Stdout, debugWithoutTime))) | ||
|
||
logger.Info("hello world") | ||
logger.Error(errors.New("fake error"), "ignore me") | ||
logger.WithValues("x", 1, "y", 2).WithValues("str", "abc").WithName("foo").WithName("bar").V(4).Info("with values, verbosity and name") | ||
|
||
// Output: | ||
// level=INFO msg="hello world" | ||
// level=ERROR msg="ignore me" err="fake error" | ||
// level=DEBUG msg="with values, verbosity and name" x=1 y=2 str=abc logger=foo/bar | ||
} | ||
|
||
func ExampleNewSlogLogger() { | ||
funcrLogger := funcr.New(func(prefix, args string) { | ||
if prefix != "" { | ||
fmt.Fprintln(os.Stdout, prefix, args) | ||
} else { | ||
fmt.Fprintln(os.Stdout, args) | ||
} | ||
}, funcr.Options{ | ||
Verbosity: 10, | ||
}) | ||
|
||
logger := slogr.NewSlogLogger(funcrLogger) | ||
logger.Info("hello world") | ||
logger.Error("ignore me", "err", errors.New("fake error")) | ||
logger.With("x", 1, "y", 2).WithGroup("group").With("str", "abc").Warn("with values and group") | ||
|
||
logger = slogr.NewSlogLogger(funcrLogger.V(int(-slog.LevelDebug))) | ||
logger.Info("info message reduced to debug level") | ||
|
||
// Output: | ||
// "level"=0 "msg"="hello world" | ||
// "msg"="ignore me" "error"=null "err"="fake error" | ||
// "level"=0 "msg"="with values and group" "x"=1 "y"=2 "group.str"="abc" | ||
// "level"=4 "msg"="info message reduced to debug level" | ||
} | ||
|
||
func TestWithCallDepth(t *testing.T) { | ||
debugWithCaller := *debugWithoutTime | ||
debugWithCaller.AddSource = true | ||
var buffer bytes.Buffer | ||
logger := slogr.New(slog.New(slog.NewTextHandler(&buffer, &debugWithCaller))) | ||
|
||
logHelper(logger) | ||
_, file, line, _ := runtime.Caller(0) | ||
expectedSource := fmt.Sprintf("%s:%d", path.Base(file), line-1) | ||
actual := buffer.String() | ||
if !strings.Contains(actual, expectedSource) { | ||
t.Errorf("expected log entry with %s as caller source code location, got instead:\n%s", expectedSource, actual) | ||
} | ||
} | ||
|
||
func logHelper(logger logr.Logger) { | ||
logger.WithCallDepth(1).Info("hello") | ||
} |
Oops, something went wrong.