golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/slog/attr.go (about) 1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slog 6 7 import ( 8 "fmt" 9 "time" 10 ) 11 12 // An Attr is a key-value pair. 13 type Attr struct { 14 Key string 15 Value Value 16 } 17 18 // String returns an Attr for a string value. 19 func String(key, value string) Attr { 20 return Attr{key, StringValue(value)} 21 } 22 23 // Int64 returns an Attr for an int64. 24 func Int64(key string, value int64) Attr { 25 return Attr{key, Int64Value(value)} 26 } 27 28 // Int converts an int to an int64 and returns 29 // an Attr with that value. 30 func Int(key string, value int) Attr { 31 return Int64(key, int64(value)) 32 } 33 34 // Uint64 returns an Attr for a uint64. 35 func Uint64(key string, v uint64) Attr { 36 return Attr{key, Uint64Value(v)} 37 } 38 39 // Float64 returns an Attr for a floating-point number. 40 func Float64(key string, v float64) Attr { 41 return Attr{key, Float64Value(v)} 42 } 43 44 // Bool returns an Attr for a bool. 45 func Bool(key string, v bool) Attr { 46 return Attr{key, BoolValue(v)} 47 } 48 49 // Time returns an Attr for a time.Time. 50 // It discards the monotonic portion. 51 func Time(key string, v time.Time) Attr { 52 return Attr{key, TimeValue(v)} 53 } 54 55 // Duration returns an Attr for a time.Duration. 56 func Duration(key string, v time.Duration) Attr { 57 return Attr{key, DurationValue(v)} 58 } 59 60 // Group returns an Attr for a Group Value. 61 // The first argument is the key; the remaining arguments 62 // are converted to Attrs as in [Logger.Log]. 63 // 64 // Use Group to collect several key-value pairs under a single 65 // key on a log line, or as the result of LogValue 66 // in order to log a single value as multiple Attrs. 67 func Group(key string, args ...any) Attr { 68 return Attr{key, GroupValue(argsToAttrSlice(args)...)} 69 } 70 71 func argsToAttrSlice(args []any) []Attr { 72 var ( 73 attr Attr 74 attrs []Attr 75 ) 76 for len(args) > 0 { 77 attr, args = argsToAttr(args) 78 attrs = append(attrs, attr) 79 } 80 return attrs 81 } 82 83 // Any returns an Attr for the supplied value. 84 // See [Value.AnyValue] for how values are treated. 85 func Any(key string, value any) Attr { 86 return Attr{key, AnyValue(value)} 87 } 88 89 // Equal reports whether a and b have equal keys and values. 90 func (a Attr) Equal(b Attr) bool { 91 return a.Key == b.Key && a.Value.Equal(b.Value) 92 } 93 94 func (a Attr) String() string { 95 return fmt.Sprintf("%s=%s", a.Key, a.Value) 96 } 97 98 // isEmpty reports whether a has an empty key and a nil value. 99 // That can be written as Attr{} or Any("", nil). 100 func (a Attr) isEmpty() bool { 101 return a.Key == "" && a.Value.num == 0 && a.Value.any == nil 102 }