Debian Codegraph @

log/keyvalue.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 //go:generate stringer -type=Kind -trimprefix=Kind
5
6 package log // import "go.opentelemetry.io/otel/log"
7
8 import (
9 "bytes"
10 "cmp"
11 "errors"
12 "fmt"
13 "math"
14 "slices"
15 "strconv"
16 "unsafe"
17
18 "go.opentelemetry.io/otel/attribute"
19 "go.opentelemetry.io/otel/internal/global"
20 )
21
22 // errKind is logged when a Value is decoded to an incompatible type.
23 var errKind = errors.New("invalid Kind")
24
25 // Kind is the kind of a [Value].
26 type Kind int
27
28 // Kind values.
29 const (
30 KindEmpty Kind = iota
31 KindBool
32 KindFloat64
33 KindInt64
34 KindString
35 KindBytes
36 KindSlice
37 KindMap
38 )
39
40 // A Value represents a structured log value.
41 // A zero value is valid and represents an empty value.
42 type Value struct {
43 // Ensure forward compatibility by explicitly making this not comparable.
44 noCmp [0]func() //nolint: unused // This is indeed used.
45
46 // num holds the value for Int64, Float64, and Bool. It holds the length
47 // for String, Bytes, Slice, Map.
48 num uint64
49 // any holds either the KindBool, KindInt64, KindFloat64, stringptr,
50 // bytesptr, sliceptr, or mapptr. If KindBool, KindInt64, or KindFloat64
51 // then the value of Value is in num as described above. Otherwise, it
52 // contains the value wrapped in the appropriate type.
53 any any
54 }
55
56 type (
57 // sliceptr represents a value in Value.any for KindString Values.
58 stringptr *byte
59 // bytesptr represents a value in Value.any for KindBytes Values.
60 bytesptr *byte
61 // sliceptr represents a value in Value.any for KindSlice Values.
62 sliceptr *Value
63 // mapptr represents a value in Value.any for KindMap Values.
64 mapptr *KeyValue
65 )
66
67 // StringValue returns a new [Value] for a string.
68 func StringValue(v string) Value {
69 return Value{
70 num: uint64(len(v)),
71 any: stringptr(unsafe.StringData(v)),
72 }
73 }
74
75 // IntValue returns a [Value] for an int.
76 func IntValue(v int) Value { return Int64Value(int64(v)) }
77
78 // Int64Value returns a [Value] for an int64.
79 func Int64Value(v int64) Value {
80 // This can be later converted back to int64 (overflow not checked).
81 return Value{num: uint64(v), any: KindInt64} // nolint:gosec
82 }
83
84 // Float64Value returns a [Value] for a float64.
85 func Float64Value(v float64) Value {
86 return Value{num: math.Float64bits(v), any: KindFloat64}
87 }
88
89 // BoolValue returns a [Value] for a bool.
90 func BoolValue(v bool) Value { //nolint:revive // Not a control flag.
91 var n uint64
92 if v {
93 n = 1
94 }
95 return Value{num: n, any: KindBool}
96 }
97
98 // BytesValue returns a [Value] for a byte slice. The passed slice must not be
99 // changed after it is passed.
100 func BytesValue(v []byte) Value {
101 return Value{
102 num: uint64(len(v)),
103 any: bytesptr(unsafe.SliceData(v)),
104 }
105 }
106
107 // SliceValue returns a [Value] for a slice of [Value]. The passed slice must
108 // not be changed after it is passed.
109 func SliceValue(vs ...Value) Value {
110 return Value{
111 num: uint64(len(vs)),
112 any: sliceptr(unsafe.SliceData(vs)),
113 }
114 }
115
116 // MapValue returns a new [Value] for a slice of key-value pairs. The passed
117 // slice must not be changed after it is passed.
118 func MapValue(kvs ...KeyValue) Value {
119 return Value{
120 num: uint64(len(kvs)),
121 any: mapptr(unsafe.SliceData(kvs)),
122 }
123 }
124
125 // AsString returns the value held by v as a string.
126 func (v Value) AsString() string {
127 if sp, ok := v.any.(stringptr); ok {
128 return unsafe.String(sp, v.num)
129 }
130 global.Error(errKind, "AsString", "Kind", v.Kind())
131 return ""
132 }
133
134 // asString returns the value held by v as a string. It will panic if the Value
135 // is not KindString.
136 func (v Value) asString() string {
137 return unsafe.String(v.any.(stringptr), v.num)
138 }
139
140 // AsInt64 returns the value held by v as an int64.
141 func (v Value) AsInt64() int64 {
142 if v.Kind() != KindInt64 {
143 global.Error(errKind, "AsInt64", "Kind", v.Kind())
144 return 0
145 }
146 return v.asInt64()
147 }
148
149 // asInt64 returns the value held by v as an int64. If v is not of KindInt64,
150 // this will return garbage.
151 func (v Value) asInt64() int64 {
152 // Assumes v.num was a valid int64 (overflow not checked).
153 return int64(v.num) // nolint: gosec
154 }
155
156 // AsBool returns the value held by v as a bool.
157 func (v Value) AsBool() bool {
158 if v.Kind() != KindBool {
159 global.Error(errKind, "AsBool", "Kind", v.Kind())
160 return false
161 }
162 return v.asBool()
163 }
164
165 // asBool returns the value held by v as a bool. If v is not of KindBool, this
166 // will return garbage.
167 func (v Value) asBool() bool { return v.num == 1 }
168
169 // AsFloat64 returns the value held by v as a float64.
170 func (v Value) AsFloat64() float64 {
171 if v.Kind() != KindFloat64 {
172 global.Error(errKind, "AsFloat64", "Kind", v.Kind())
173 return 0
174 }
175 return v.asFloat64()
176 }
177
178 // asFloat64 returns the value held by v as a float64. If v is not of
179 // KindFloat64, this will return garbage.
180 func (v Value) asFloat64() float64 { return math.Float64frombits(v.num) }
181
182 // AsBytes returns the value held by v as a []byte.
183 func (v Value) AsBytes() []byte {
184 if sp, ok := v.any.(bytesptr); ok {
185 return unsafe.Slice((*byte)(sp), v.num)
186 }
187 global.Error(errKind, "AsBytes", "Kind", v.Kind())
188 return nil
189 }
190
191 // asBytes returns the value held by v as a []byte. It will panic if the Value
192 // is not KindBytes.
193 func (v Value) asBytes() []byte {
194 return unsafe.Slice((*byte)(v.any.(bytesptr)), v.num)
195 }
196
197 // AsSlice returns the value held by v as a []Value.
198 func (v Value) AsSlice() []Value {
199 if sp, ok := v.any.(sliceptr); ok {
200 return unsafe.Slice((*Value)(sp), v.num)
201 }
202 global.Error(errKind, "AsSlice", "Kind", v.Kind())
203 return nil
204 }
205
206 // asSlice returns the value held by v as a []Value. It will panic if the Value
207 // is not KindSlice.
208 func (v Value) asSlice() []Value {
209 return unsafe.Slice((*Value)(v.any.(sliceptr)), v.num)
210 }
211
212 // AsMap returns the value held by v as a []KeyValue.
213 func (v Value) AsMap() []KeyValue {
214 if sp, ok := v.any.(mapptr); ok {
215 return unsafe.Slice((*KeyValue)(sp), v.num)
216 }
217 global.Error(errKind, "AsMap", "Kind", v.Kind())
218 return nil
219 }
220
221 // asMap returns the value held by v as a []KeyValue. It will panic if the
222 // Value is not KindMap.
223 func (v Value) asMap() []KeyValue {
224 return unsafe.Slice((*KeyValue)(v.any.(mapptr)), v.num)
225 }
226
227 // Kind returns the Kind of v.
228 func (v Value) Kind() Kind {
229 switch x := v.any.(type) {
230 case Kind:
231 return x
232 case stringptr:
233 return KindString
234 case bytesptr:
235 return KindBytes
236 case sliceptr:
237 return KindSlice
238 case mapptr:
239 return KindMap
240 default:
241 return KindEmpty
242 }
243 }
244
245 // Empty reports whether v does not hold any value.
246 func (v Value) Empty() bool { return v.Kind() == KindEmpty }
247
248 // Equal reports whether v is equal to w.
249 func (v Value) Equal(w Value) bool {
250 k1 := v.Kind()
251 k2 := w.Kind()
252 if k1 != k2 {
253 return false
254 }
255 switch k1 {
256 case KindInt64, KindBool:
257 return v.num == w.num
258 case KindString:
259 return v.asString() == w.asString()
260 case KindFloat64:
261 return v.asFloat64() == w.asFloat64()
262 case KindSlice:
263 return slices.EqualFunc(v.asSlice(), w.asSlice(), Value.Equal)
264 case KindMap:
265 sv := sortMap(v.asMap())
266 sw := sortMap(w.asMap())
267 return slices.EqualFunc(sv, sw, KeyValue.Equal)
268 case KindBytes:
269 return bytes.Equal(v.asBytes(), w.asBytes())
270 case KindEmpty:
271 return true
272 default:
273 global.Error(errKind, "Equal", "Kind", k1)
274 return false
275 }
276 }
277
278 func sortMap(m []KeyValue) []KeyValue {
279 sm := make([]KeyValue, len(m))
280 copy(sm, m)
281 slices.SortFunc(sm, func(a, b KeyValue) int {
282 return cmp.Compare(a.Key, b.Key)
283 })
284
285 return sm
286 }
287
288 // String returns Value's value as a string, formatted like [fmt.Sprint].
289 //
290 // The returned string is meant for debugging;
291 // the string representation is not stable.
292 func (v Value) String() string {
293 switch v.Kind() {
294 case KindString:
295 return v.asString()
296 case KindInt64:
297 // Assumes v.num was a valid int64 (overflow not checked).
298 return strconv.FormatInt(int64(v.num), 10) // nolint: gosec
299 case KindFloat64:
300 return strconv.FormatFloat(v.asFloat64(), 'g', -1, 64)
301 case KindBool:
302 return strconv.FormatBool(v.asBool())
303 case KindBytes:
304 return fmt.Sprint(v.asBytes()) // nolint:staticcheck // Use fmt.Sprint to encode as slice.
305 case KindMap:
306 return fmt.Sprint(v.asMap())
307 case KindSlice:
308 return fmt.Sprint(v.asSlice())
309 case KindEmpty:
310 return "<nil>"
311 default:
312 // Try to handle this as gracefully as possible.
313 //
314 // Don't panic here. The goal here is to have developers find this
315 // first if a slog.Kind is is not handled. It is
316 // preferable to have user's open issue asking why their attributes
317 // have a "unhandled: " prefix than say that their code is panicking.
318 return fmt.Sprintf("<unhandled log.Kind: %s>", v.Kind())
319 }
320 }
321
322 // A KeyValue is a key-value pair used to represent a log attribute (a
323 // superset of [go.opentelemetry.io/otel/attribute.KeyValue]) and map item.
324 type KeyValue struct {
325 Key string
326 Value Value
327 }
328
329 // Equal reports whether a is equal to b.
330 func (a KeyValue) Equal(b KeyValue) bool {
331 return a.Key == b.Key && a.Value.Equal(b.Value)
332 }
333
334 // String returns a KeyValue for a string value.
335 func String(key, value string) KeyValue {
336 return KeyValue{key, StringValue(value)}
337 }
338
339 // Int64 returns a KeyValue for an int64 value.
340 func Int64(key string, value int64) KeyValue {
341 return KeyValue{key, Int64Value(value)}
342 }
343
344 // Int returns a KeyValue for an int value.
345 func Int(key string, value int) KeyValue {
346 return KeyValue{key, IntValue(value)}
347 }
348
349 // Float64 returns a KeyValue for a float64 value.
350 func Float64(key string, value float64) KeyValue {
351 return KeyValue{key, Float64Value(value)}
352 }
353
354 // Bool returns a KeyValue for a bool value.
355 func Bool(key string, value bool) KeyValue {
356 return KeyValue{key, BoolValue(value)}
357 }
358
359 // Bytes returns a KeyValue for a []byte value.
360 // The passed slice must not be changed after it is passed.
361 func Bytes(key string, value []byte) KeyValue {
362 return KeyValue{key, BytesValue(value)}
363 }
364
365 // Slice returns a KeyValue for a []Value value.
366 // The passed slice must not be changed after it is passed.
367 func Slice(key string, value ...Value) KeyValue {
368 return KeyValue{key, SliceValue(value...)}
369 }
370
371 // Map returns a KeyValue for a map value.
372 // The passed slice must not be changed after it is passed.
373 func Map(key string, value ...KeyValue) KeyValue {
374 return KeyValue{key, MapValue(value...)}
375 }
376
377 // Empty returns a KeyValue with an empty value.
378 func Empty(key string) KeyValue {
379 return KeyValue{key, Value{}}
380 }
381
382 // String returns key-value pair as a string, formatted like "key:value".
383 //
384 // The returned string is meant for debugging;
385 // the string representation is not stable.
386 func (a KeyValue) String() string {
387 return fmt.Sprintf("%s:%s", a.Key, a.Value)
388 }
389
390 // ValueFromAttribute converts [attribute.Value] to [Value].
391 func ValueFromAttribute(value attribute.Value) Value {
392 switch value.Type() {
393 case attribute.EMPTY:
394 return Value{}
395 case attribute.BOOL:
396 return BoolValue(value.AsBool())
397 case attribute.BOOLSLICE:
398 val := value.AsBoolSlice()
399 res := make([]Value, 0, len(val))
400 for _, v := range val {
401 res = append(res, BoolValue(v))
402 }
403 return SliceValue(res...)
404 case attribute.INT64:
405 return Int64Value(value.AsInt64())
406 case attribute.INT64SLICE:
407 val := value.AsInt64Slice()
408 res := make([]Value, 0, len(val))
409 for _, v := range val {
410 res = append(res, Int64Value(v))
411 }
412 return SliceValue(res...)
413 case attribute.FLOAT64:
414 return Float64Value(value.AsFloat64())
415 case attribute.FLOAT64SLICE:
416 val := value.AsFloat64Slice()
417 res := make([]Value, 0, len(val))
418 for _, v := range val {
419 res = append(res, Float64Value(v))
420 }
421 return SliceValue(res...)
422 case attribute.STRING:
423 return StringValue(value.AsString())
424 case attribute.STRINGSLICE:
425 val := value.AsStringSlice()
426 res := make([]Value, 0, len(val))
427 for _, v := range val {
428 res = append(res, StringValue(v))
429 }
430 return SliceValue(res...)
431 }
432 // This code should never be reached
433 // as log attributes are a superset of standard attributes.
434 panic("unknown attribute type")
435 }
436
437 // KeyValueFromAttribute converts [attribute.KeyValue] to [KeyValue].
438 func KeyValueFromAttribute(kv attribute.KeyValue) KeyValue {
439 return KeyValue{
440 Key: string(kv.Key),
441 Value: ValueFromAttribute(kv.Value),
442 }
443 }