forked from alibaba/loongcollector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetric_example.go
74 lines (65 loc) · 2.5 KB
/
metric_example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2021 iLogtail Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package example
import (
"math/rand"
"time"
"github.com/alibaba/ilogtail"
"github.com/alibaba/ilogtail/helper"
"github.com/alibaba/ilogtail/pkg/util"
)
// MetricsExample struct implements the MetricInput interface.
// The plugin has a counter field, which would be increment every 5 seconds.
// And, the value of this counter will be sent as metrics data.
type MetricsExample struct {
counter int
gauge int
commonLabels helper.KeyValues
labels string
}
// Init method would be triggered before working. In the example plugin, we set the initial
// value of counter to 100. And we return 0 to use the default trigger interval.
func (m *MetricsExample) Init(context ilogtail.Context) (int, error) {
// set the initial value
m.counter = 100
// use helper.KeyValues to store metric labels
m.commonLabels.Append("hostname", util.GetHostName())
m.commonLabels.Append("ip", util.GetIPAddress())
// convert the commonLabels to string to reduce memory cost because the labels is the fixed value.
m.labels = m.commonLabels.String()
return 0, nil
}
func (m *MetricsExample) Description() string {
return "This is a metric input example plugin, this plugin would show how to write a simple metric input plugin."
}
// Collect is called every trigger interval to collect the metrics and send them to the collector.
func (m *MetricsExample) Collect(collector ilogtail.Collector) error {
// counter increment
m.counter++
// create a random value as gauge value
//nolint:gosec
m.gauge = rand.Intn(100)
// collect the metrics
helper.AddMetric(collector, "example_counter", time.Now(), m.labels, float64(m.counter))
helper.AddMetric(collector, "example_gauge", time.Now(), m.labels, float64(m.gauge))
return nil
}
// Register the plugin to the MetricInputs array.
func init() {
ilogtail.MetricInputs["metric_input_example"] = func() ilogtail.MetricInput {
return &MetricsExample{
// here you could set default value.
}
}
}