From d38dfb6f82d4a7f11c2b081497de6f368062ac25 Mon Sep 17 00:00:00 2001 From: jiangyong Date: Sun, 21 Jan 2024 22:54:16 +0800 Subject: [PATCH] count/duration --- metric/config.go | 4 +++- metric/metric.go | 15 ++++++++++++++- metric/service.go | 45 +++++++++++++++++++++++++++++++++++++++------ 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/metric/config.go b/metric/config.go index 2b88581..0cb26d0 100644 --- a/metric/config.go +++ b/metric/config.go @@ -1,7 +1,9 @@ package metric var ( - serv *service + serv *service + TypeCount = "count" + TypeDuration = "duration" ) type Config struct { diff --git a/metric/metric.go b/metric/metric.go index 006a177..dc5c154 100644 --- a/metric/metric.go +++ b/metric/metric.go @@ -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(), }) diff --git a/metric/service.go b/metric/service.go index 935a2f7..5afbc47 100644 --- a/metric/service.go +++ b/metric/service.go @@ -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 +}