github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/selfmonitor/metrics_record.go (about) 1 // Copyright 2021 iLogtail Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package selfmonitor 16 17 import ( 18 "encoding/json" 19 "sync" 20 ) 21 22 const SelfMetricNameKey = "__name__" 23 const MetricLabelPrefix = "labels" 24 const MetricCounterPrefix = "counters" 25 const MetricGaugePrefix = "gauges" 26 27 type MetricsRecord struct { 28 Labels []LabelPair 29 30 sync.RWMutex 31 MetricCollectors []MetricCollector 32 } 33 34 func (m *MetricsRecord) insertLabels(record map[string]string) { 35 labels := map[string]string{} 36 for _, label := range m.Labels { 37 labels[label.Key] = label.Value 38 } 39 labelsStr, _ := json.Marshal(labels) 40 record[MetricLabelPrefix] = string(labelsStr) 41 } 42 43 func (m *MetricsRecord) RegisterMetricCollector(collector MetricCollector) { 44 m.Lock() 45 defer m.Unlock() 46 m.MetricCollectors = append(m.MetricCollectors, collector) 47 } 48 49 // ExportMetricRecords is used for exporting metrics records. 50 // It will replace Serialize in the future. 51 func (m *MetricsRecord) ExportMetricRecords() map[string]string { 52 m.RLock() 53 defer m.RUnlock() 54 55 record := map[string]string{} 56 counters := map[string]string{} 57 gauges := map[string]string{} 58 m.insertLabels(record) 59 for _, metricCollector := range m.MetricCollectors { 60 metrics := metricCollector.Collect() 61 for _, metric := range metrics { 62 singleMetric := metric.Export() 63 if len(singleMetric) == 0 { 64 continue 65 } 66 valueName := singleMetric[SelfMetricNameKey] 67 valueValue := singleMetric[valueName] 68 if metric.Type() == CounterType { 69 counters[valueName] = valueValue 70 } 71 if metric.Type() == GaugeType { 72 gauges[valueName] = valueValue 73 } 74 } 75 } 76 countersStr, _ := json.Marshal(counters) 77 record[MetricCounterPrefix] = string(countersStr) 78 gaugesStr, _ := json.Marshal(gauges) 79 record[MetricGaugePrefix] = string(gaugesStr) 80 return record 81 }