From 3f241610d066c8c0d406429a6a371858fd64b46e Mon Sep 17 00:00:00 2001 From: jiangyong Date: Wed, 18 Nov 2026 00:42:41 +0800 Subject: [PATCH] count --- metric/metric.go | 14 ++++++++++++++ metric/service.go | 22 ++++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/metric/metric.go b/metric/metric.go index 1725340..c200ecb 100644 --- a/metric/metric.go +++ b/metric/metric.go @@ -9,6 +9,7 @@ func Value(name string, value int64, tags map[string]string) { return } serv.add(&metric{ + Type: metricTypeValue, Metric: name, Value: value, Count: 1, @@ -16,3 +17,16 @@ func Value(name string, value int64, tags map[string]string) { Timestamp: time.Now().UnixMilli(), }) } + +func Count(name string, tags map[string]string) { + if serv == nil { + return + } + serv.add(&metric{ + Type: metricTypeCount, + Count: 1, + Metric: name, + Tags: tags, + Timestamp: time.Now().UnixMilli(), + }) +} diff --git a/metric/service.go b/metric/service.go index 3cc616d..4b83579 100644 --- a/metric/service.go +++ b/metric/service.go @@ -15,7 +15,13 @@ import ( const reportBatchSize = 500 +const ( + metricTypeValue = "value" + metricTypeCount = "count" +) + type metric struct { + Type string `json:"type"` Timestamp int64 `json:"timestamp"` Metric string `json:"metric"` Count int64 `json:"count"` @@ -196,11 +202,19 @@ func (s *service) retain(items []*aggregateItem) { } func (s *service) reportFields(m *metric) map[string]any { - var avg int64 = 0 - if m.Count > 0 && m.Value != 0 { - avg = m.Value / m.Count + + fields := make(map[string]any) + switch m.Type { + case metricTypeCount: + fields["count"] = m.Count + case metricTypeValue: + fields["value"] = m.Value + fields["count"] = m.Count + if m.Count > 0 && m.Value != 0 { + fields["avg"] = m.Value / m.Count + } } - return map[string]any{"count": m.Count, "value": m.Value, "avg": avg} + return fields } func (s *service) send(points []*reportPoint) error {