count/duration

This commit is contained in:
jiangyong 2024-01-21 22:54:16 +08:00
parent 46882eb4ce
commit d38dfb6f82
3 changed files with 56 additions and 8 deletions

View File

@ -1,7 +1,9 @@
package metric
var (
serv *service
serv *service
TypeCount = "count"
TypeDuration = "duration"
)
type Config struct {

View File

@ -4,14 +4,27 @@ import (
"time"
)
func Metric(name string, value float64, tag map[string]string) {
func Count(name string, value int64, tag map[string]string) {
if serv == nil {
return
}
serv.add(&metric{
Type: TypeCount,
Metric: name,
Value: value,
Count: 1,
Tags: tag,
Timestamp: time.Now().Unix(),
})
}
func Duration(name string, costMs int64, tag map[string]string) {
serv.add(&metric{
Type: TypeDuration,
Metric: name,
Value: costMs,
Count: 1,
Tags: tag,
Timestamp: time.Now().Unix(),
})

View File

@ -11,9 +11,13 @@ import (
)
type metric struct {
Type string `json:"type"`
Timestamp int64 `json:"timestamp"`
Metric string `json:"metric"`
Value float64 `json:"value"`
Count int64 `json:"count"`
Value int64 `json:"value"`
Max int64 `json:"max"`
Min int64 `json:"min"`
Tags map[string]string `json:"tags"`
}
@ -83,21 +87,29 @@ func (s *service) process(m *metric) {
if v, ok := s.megers[key]; ok {
v.Value += m.Value
v.Count += m.Count
v.Timestamp = m.Timestamp
if m.Value > v.Max {
v.Max = m.Value
}
if m.Value < v.Min {
v.Value = m.Min
}
return
}
m.Max = m.Value
m.Min = m.Value
s.megers[key] = m
}
func (s *service) defaultTags() map[string]string {
return map[string]string{
"hostname": s.hostname,
"host_ip": s.hostIp,
"pod_ip": s.podIp,
"service_name": s.serviceName,
}
}
func (s *service) report() {
@ -110,9 +122,7 @@ func (s *service) report() {
var p influxdb.Point
p.Measurement = v.Metric
p.Tags = v.Tags
p.Fields = map[string]interface{}{
"value": v.Value,
}
p.Fields = s.getField(v)
p.Time = time.Unix(v.Timestamp, 0)
bp.Points = append(bp.Points, p)
}
@ -132,3 +142,26 @@ func (s *service) add(m *metric) {
fmt.Println("chan is full")
}
}
func (s *service) getField(m *metric) map[string]interface{} {
if m.Type == TypeCount {
return map[string]interface{}{
"count": m.Count,
"value": m.Value,
}
}
if m.Type == TypeDuration {
avgMs := float64(m.Value) / float64(m.Count)
return map[string]interface{}{
"avg": avgMs,
"count": m.Count,
"value": m.Value,
"max": m.Max,
"min": m.Min,
}
}
return nil
}