1
2
3
4
19
20 package textlogger_test
21
22 import (
23 "errors"
24 "log/slog"
25 "os"
26 "time"
27
28 "github.com/go-logr/logr/slogr"
29 internal "k8s.io/klog/v2/internal/buffer"
30 "k8s.io/klog/v2/textlogger"
31 )
32
33 var _ slog.LogValuer = coordinates{}
34
35 type coordinates struct {
36 x, y int
37 }
38
39 func (c coordinates) LogValue() slog.Value {
40 return slog.GroupValue(slog.Attr{Key: "X", Value: slog.IntValue(c.x)}, slog.Attr{Key: "Y", Value: slog.IntValue(c.y)})
41 }
42
43 func ExampleNewLogger_Slog() {
44 ts, _ := time.Parse(time.RFC3339, "2000-12-24T12:30:40Z")
45 internal.Pid = 123
46 config := textlogger.NewConfig(
47 textlogger.FixedTime(ts),
48 textlogger.Verbosity(4),
49 textlogger.Output(os.Stdout),
50 )
51 logrLogger := textlogger.NewLogger(config)
52 slogHandler := slogr.NewSlogHandler(logrLogger)
53 slogLogger := slog.New(slogHandler)
54
55 slogLogger.Debug("A debug message")
56 slogLogger.Log(nil, slog.LevelDebug-1, "A debug message with even lower level, not printed.")
57 slogLogger.Info("An info message")
58 slogLogger.Warn("A warning")
59 slogLogger.Error("An error", "err", errors.New("fake error"))
60
61
62 slogLogger.WithGroup("top").With("int", 42, slog.Group("variables", "a", 1, "b", 2)).Info("Grouping",
63 "sub", slog.GroupValue(
64 slog.Attr{Key: "str", Value: slog.StringValue("abc")},
65 slog.Attr{Key: "bool", Value: slog.BoolValue(true)},
66 slog.Attr{Key: "bottom", Value: slog.GroupValue(slog.Attr{Key: "coordinates", Value: slog.AnyValue(coordinates{x: -1, y: -2})})},
67 ),
68 "duration", slog.DurationValue(time.Second),
69 slog.Float64("pi", 3.12),
70 "e", 2.71,
71 "moreCoordinates", coordinates{x: 100, y: 200},
72 )
73
74
75
76
77
78 logrLogger.Info("slog values",
79 "variables", slog.GroupValue(slog.Int("a", 1), slog.Int("b", 2)),
80 "duration", slog.DurationValue(time.Second),
81 "coordinates", coordinates{x: 100, y: 200},
82 )
83
84
85
86
87
88
89
90
91 }
92
View as plain text