github.com/gogf/gf/v2@v2.7.4/os/gmetric/gmetric_attribute.go (about) 1 // Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gmetric 8 9 import ( 10 "bytes" 11 "fmt" 12 "os" 13 14 "github.com/gogf/gf/v2/internal/json" 15 "github.com/gogf/gf/v2/os/gfile" 16 ) 17 18 // Attributes is a slice of Attribute. 19 type Attributes []Attribute 20 21 // Attribute is the key-value pair item for Metric. 22 type Attribute interface { 23 Key() string // The key for this attribute. 24 Value() any // The value for this attribute. 25 } 26 27 // AttributeKey is the attribute key. 28 type AttributeKey string 29 30 // Option holds the option for perform a metric operation. 31 type Option struct { 32 // Attributes holds the dynamic key-value pair metadata. 33 Attributes Attributes 34 } 35 36 // localAttribute implements interface Attribute. 37 type localAttribute struct { 38 key string 39 value any 40 } 41 42 var ( 43 hostname string 44 processPath string 45 ) 46 47 func init() { 48 hostname, _ = os.Hostname() 49 processPath = gfile.SelfPath() 50 } 51 52 // CommonAttributes returns the common used attributes for an instrument. 53 func CommonAttributes() Attributes { 54 return Attributes{ 55 NewAttribute(`os.host.name`, hostname), 56 NewAttribute(`process.path`, processPath), 57 } 58 } 59 60 // NewAttribute creates and returns an Attribute by given `key` and `value`. 61 func NewAttribute(key string, value any) Attribute { 62 return &localAttribute{ 63 key: key, 64 value: value, 65 } 66 } 67 68 // Key returns the key of the attribute. 69 func (l *localAttribute) Key() string { 70 return l.key 71 } 72 73 // Value returns the value of the attribute. 74 func (l *localAttribute) Value() any { 75 return l.value 76 } 77 78 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 79 func (l *localAttribute) MarshalJSON() ([]byte, error) { 80 return []byte(fmt.Sprintf(`{"%s":%#v}`, l.key, l.value)), nil 81 } 82 83 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 84 func (attrs Attributes) String() string { 85 bs, _ := attrs.MarshalJSON() 86 return string(bs) 87 } 88 89 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 90 func (attrs Attributes) MarshalJSON() ([]byte, error) { 91 var ( 92 bs []byte 93 err error 94 buffer = bytes.NewBuffer(nil) 95 ) 96 buffer.WriteByte('[') 97 for _, attr := range attrs { 98 bs, err = json.Marshal(attr) 99 if err != nil { 100 return nil, err 101 } 102 if buffer.Len() > 1 { 103 buffer.WriteByte(',') 104 } 105 buffer.Write(bs) 106 } 107 buffer.WriteByte(']') 108 return buffer.Bytes(), nil 109 }