| 1 |
//go:build go1.21 |
| 2 |
|
| 3 |
/* |
| 4 |
Copyright 2023 The logr Authors. |
| 5 |
|
| 6 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
you may not use this file except in compliance with the License. |
| 8 |
You may obtain a copy of the License at |
| 9 |
|
| 10 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
|
| 12 |
Unless required by applicable law or agreed to in writing, software |
| 13 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
See the License for the specific language governing permissions and |
| 16 |
limitations under the License. |
| 17 |
*/ |
| 18 |
|
| 19 |
package logr_test |
| 20 |
|
| 21 |
import ( |
| 22 |
"errors" |
| 23 |
"fmt" |
| 24 |
"log/slog" |
| 25 |
"os" |
| 26 |
|
| 27 |
"github.com/go-logr/logr" |
| 28 |
"github.com/go-logr/logr/funcr" |
| 29 |
) |
| 30 |
|
| 31 |
var debugWithoutTime = &slog.HandlerOptions{ |
| 32 |
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { |
| 33 |
if a.Key == "time" { |
| 34 |
return slog.Attr{} |
| 35 |
} |
| 36 |
return a |
| 37 |
}, |
| 38 |
Level: slog.LevelDebug, |
| 39 |
} |
| 40 |
|
| 41 |
func ExampleFromSlogHandler() { |
| 42 |
logrLogger := logr.FromSlogHandler(slog.NewTextHandler(os.Stdout, debugWithoutTime)) |
| 43 |
|
| 44 |
logrLogger.Info("hello world") |
| 45 |
logrLogger.Error(errors.New("fake error"), "ignore me") |
| 46 |
logrLogger.WithValues("x", 1, "y", 2).WithValues("str", "abc").WithName("foo").WithName("bar").V(4).Info("with values, verbosity and name") |
| 47 |
|
| 48 |
// Output: |
| 49 |
// level=INFO msg="hello world" |
| 50 |
// level=ERROR msg="ignore me" err="fake error" |
| 51 |
// level=DEBUG msg="with values, verbosity and name" x=1 y=2 str=abc logger=foo/bar |
| 52 |
} |
| 53 |
|
| 54 |
func ExampleToSlogHandler() { |
| 55 |
funcrLogger := funcr.New(func(prefix, args string) { |
| 56 |
if prefix != "" { |
| 57 |
fmt.Println(prefix, args) |
| 58 |
} else { |
| 59 |
fmt.Println(args) |
| 60 |
} |
| 61 |
}, funcr.Options{ |
| 62 |
Verbosity: 10, |
| 63 |
}) |
| 64 |
|
| 65 |
slogLogger := slog.New(logr.ToSlogHandler(funcrLogger)) |
| 66 |
slogLogger.Info("hello world") |
| 67 |
slogLogger.Error("ignore me", "err", errors.New("fake error")) |
| 68 |
slogLogger.With("x", 1, "y", 2).WithGroup("group").With("str", "abc").Warn("with values and group") |
| 69 |
|
| 70 |
slogLogger = slog.New(logr.ToSlogHandler(funcrLogger.V(int(-slog.LevelDebug)))) |
| 71 |
slogLogger.Info("info message reduced to debug level") |
| 72 |
|
| 73 |
// Output: |
| 74 |
// "level"=0 "msg"="hello world" |
| 75 |
// "msg"="ignore me" "error"=null "err"="fake error" |
| 76 |
// "level"=0 "msg"="with values and group" "x"=1 "y"=2 "group"={"str"="abc"} |
| 77 |
// "level"=4 "msg"="info message reduced to debug level" |
| 78 |
} |