| 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 |
| 20 |
|
| 21 |
import ( |
| 22 |
"context" |
| 23 |
"log/slog" |
| 24 |
) |
| 25 |
|
| 26 |
type slogHandler struct { |
| 27 |
// May be nil, in which case all logs get discarded. |
| 28 |
sink LogSink |
| 29 |
// Non-nil if sink is non-nil and implements SlogSink. |
| 30 |
slogSink SlogSink |
| 31 |
|
| 32 |
// groupPrefix collects values from WithGroup calls. It gets added as |
| 33 |
// prefix to value keys when handling a log record. |
| 34 |
groupPrefix string |
| 35 |
|
| 36 |
// levelBias can be set when constructing the handler to influence the |
| 37 |
// slog.Level of log records. A positive levelBias reduces the |
| 38 |
// slog.Level value. slog has no API to influence this value after the |
| 39 |
// handler got created, so it can only be set indirectly through |
| 40 |
// Logger.V. |
| 41 |
levelBias slog.Level |
| 42 |
} |
| 43 |
|
| 44 |
var _ slog.Handler = &slogHandler{} |
| 45 |
|
| 46 |
// groupSeparator is used to concatenate WithGroup names and attribute keys. |
| 47 |
const groupSeparator = "." |
| 48 |
|
| 49 |
// GetLevel is used for black box unit testing. |
| 50 |
func (l *slogHandler) GetLevel() slog.Level { |
| 51 |
return l.levelBias |
| 52 |
} |
| 53 |
|
| 54 |
func (l *slogHandler) Enabled(_ context.Context, level slog.Level) bool { |
| 55 |
return l.sink != nil && (level >= slog.LevelError || l.sink.Enabled(l.levelFromSlog(level))) |
| 56 |
} |
| 57 |
|
| 58 |
func (l *slogHandler) Handle(ctx context.Context, record slog.Record) error { |
| 59 |
if l.slogSink != nil { |
| 60 |
// Only adjust verbosity level of log entries < slog.LevelError. |
| 61 |
if record.Level < slog.LevelError { |
| 62 |
record.Level -= l.levelBias |
| 63 |
} |
| 64 |
return l.slogSink.Handle(ctx, record) |
| 65 |
} |
| 66 |
|
| 67 |
// No need to check for nil sink here because Handle will only be called |
| 68 |
// when Enabled returned true. |
| 69 |
|
| 70 |
kvList := make([]any, 0, 2*record.NumAttrs()) |
| 71 |
record.Attrs(func(attr slog.Attr) bool { |
| 72 |
kvList = attrToKVs(attr, l.groupPrefix, kvList) |
| 73 |
return true |
| 74 |
}) |
| 75 |
if record.Level >= slog.LevelError { |
| 76 |
l.sinkWithCallDepth().Error(nil, record.Message, kvList...) |
| 77 |
} else { |
| 78 |
level := l.levelFromSlog(record.Level) |
| 79 |
l.sinkWithCallDepth().Info(level, record.Message, kvList...) |
| 80 |
} |
| 81 |
return nil |
| 82 |
} |
| 83 |
|
| 84 |
// sinkWithCallDepth adjusts the stack unwinding so that when Error or Info |
| 85 |
// are called by Handle, code in slog gets skipped. |
| 86 |
// |
| 87 |
// This offset currently (Go 1.21.0) works for calls through |
| 88 |
// slog.New(ToSlogHandler(...)). There's no guarantee that the call |
| 89 |
// chain won't change. Wrapping the handler will also break unwinding. It's |
| 90 |
// still better than not adjusting at all.... |
| 91 |
// |
| 92 |
// This cannot be done when constructing the handler because FromSlogHandler needs |
| 93 |
// access to the original sink without this adjustment. A second copy would |
| 94 |
// work, but then WithAttrs would have to be called for both of them. |
| 95 |
func (l *slogHandler) sinkWithCallDepth() LogSink { |
| 96 |
if sink, ok := l.sink.(CallDepthLogSink); ok { |
| 97 |
return sink.WithCallDepth(2) |
| 98 |
} |
| 99 |
return l.sink |
| 100 |
} |
| 101 |
|
| 102 |
func (l *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 103 |
if l.sink == nil || len(attrs) == 0 { |
| 104 |
return l |
| 105 |
} |
| 106 |
|
| 107 |
clone := *l |
| 108 |
if l.slogSink != nil { |
| 109 |
clone.slogSink = l.slogSink.WithAttrs(attrs) |
| 110 |
clone.sink = clone.slogSink |
| 111 |
} else { |
| 112 |
kvList := make([]any, 0, 2*len(attrs)) |
| 113 |
for _, attr := range attrs { |
| 114 |
kvList = attrToKVs(attr, l.groupPrefix, kvList) |
| 115 |
} |
| 116 |
clone.sink = l.sink.WithValues(kvList...) |
| 117 |
} |
| 118 |
return &clone |
| 119 |
} |
| 120 |
|
| 121 |
func (l *slogHandler) WithGroup(name string) slog.Handler { |
| 122 |
if l.sink == nil { |
| 123 |
return l |
| 124 |
} |
| 125 |
if name == "" { |
| 126 |
// slog says to inline empty groups |
| 127 |
return l |
| 128 |
} |
| 129 |
clone := *l |
| 130 |
if l.slogSink != nil { |
| 131 |
clone.slogSink = l.slogSink.WithGroup(name) |
| 132 |
clone.sink = clone.slogSink |
| 133 |
} else { |
| 134 |
clone.groupPrefix = addPrefix(clone.groupPrefix, name) |
| 135 |
} |
| 136 |
return &clone |
| 137 |
} |
| 138 |
|
| 139 |
// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups |
| 140 |
// and other details of slog. |
| 141 |
func attrToKVs(attr slog.Attr, groupPrefix string, kvList []any) []any { |
| 142 |
attrVal := attr.Value.Resolve() |
| 143 |
if attrVal.Kind() == slog.KindGroup { |
| 144 |
groupVal := attrVal.Group() |
| 145 |
grpKVs := make([]any, 0, 2*len(groupVal)) |
| 146 |
prefix := groupPrefix |
| 147 |
if attr.Key != "" { |
| 148 |
prefix = addPrefix(groupPrefix, attr.Key) |
| 149 |
} |
| 150 |
for _, attr := range groupVal { |
| 151 |
grpKVs = attrToKVs(attr, prefix, grpKVs) |
| 152 |
} |
| 153 |
kvList = append(kvList, grpKVs...) |
| 154 |
} else if attr.Key != "" { |
| 155 |
kvList = append(kvList, addPrefix(groupPrefix, attr.Key), attrVal.Any()) |
| 156 |
} |
| 157 |
|
| 158 |
return kvList |
| 159 |
} |
| 160 |
|
| 161 |
func addPrefix(prefix, name string) string { |
| 162 |
if prefix == "" { |
| 163 |
return name |
| 164 |
} |
| 165 |
if name == "" { |
| 166 |
return prefix |
| 167 |
} |
| 168 |
return prefix + groupSeparator + name |
| 169 |
} |
| 170 |
|
| 171 |
// levelFromSlog adjusts the level by the logger's verbosity and negates it. |
| 172 |
// It ensures that the result is >= 0. This is necessary because the result is |
| 173 |
// passed to a LogSink and that API did not historically document whether |
| 174 |
// levels could be negative or what that meant. |
| 175 |
// |
| 176 |
// Some example usage: |
| 177 |
// |
| 178 |
// logrV0 := getMyLogger() |
| 179 |
// logrV2 := logrV0.V(2) |
| 180 |
// slogV2 := slog.New(logr.ToSlogHandler(logrV2)) |
| 181 |
// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6) |
| 182 |
// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2) |
| 183 |
// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0) |
| 184 |
func (l *slogHandler) levelFromSlog(level slog.Level) int { |
| 185 |
result := -level |
| 186 |
result += l.levelBias // in case the original Logger had a V level |
| 187 |
if result < 0 { |
| 188 |
result = 0 // because LogSink doesn't expect negative V levels |
| 189 |
} |
| 190 |
return int(result) |
| 191 |
} |