Skip to content

Commit

Permalink
up
Browse files Browse the repository at this point in the history
  • Loading branch information
gqcn committed Nov 16, 2023
1 parent 9b08803 commit c5c8f82
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
51 changes: 51 additions & 0 deletions os/gmetric/gmetric_attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
package gmetric

import (
"bytes"
"fmt"
"os"

"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/os/gfile"
)

// localAttribute implements interface Attribute.
Expand All @@ -16,6 +21,24 @@ type localAttribute struct {
value any
}

var (
hostname string
processPath string
)

func init() {
hostname, _ = os.Hostname()
processPath = gfile.SelfPath()
}

// CommonAttributes returns the common used attributes for an instrument.
func CommonAttributes() Attributes {
return Attributes{
NewAttribute(`os.host.name`, hostname),
NewAttribute(`process.path`, processPath),
}
}

// NewAttribute creates and returns an Attribute by given `key` and `value`.
func NewAttribute(key string, value any) Attribute {
return &localAttribute{
Expand All @@ -38,3 +61,31 @@ func (l *localAttribute) Value() any {
func (l *localAttribute) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`{"%s":%#v}`, l.key, l.value)), nil
}

// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (attrs Attributes) String() string {
bs, _ := attrs.MarshalJSON()
return string(bs)
}

// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (attrs Attributes) MarshalJSON() ([]byte, error) {
var (
bs []byte
err error
buffer = bytes.NewBuffer(nil)
)
buffer.WriteByte('[')
for _, attr := range attrs {
bs, err = json.Marshal(attr)
if err != nil {
return nil, err
}
if buffer.Len() > 1 {
buffer.WriteByte(',')
}
buffer.Write(bs)
}
buffer.WriteByte(']')
return buffer.Bytes(), nil
}
9 changes: 9 additions & 0 deletions os/gmetric/gmetric_z_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package gmetric_test

import (
"fmt"
"testing"

"github.com/gogf/gf/v2/os/gmetric"
Expand Down Expand Up @@ -92,3 +93,11 @@ func Test_Histogram(t *testing.T) {
t.Assert(counter.Buckets(), config.Buckets)
})
}

func Test_CommonAttributes(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
commonAttributes := gmetric.CommonAttributes()
t.AssertGT(len(commonAttributes), 1)
fmt.Println(commonAttributes)
})
}

0 comments on commit c5c8f82

Please sign in to comment.