-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
parser.go
86 lines (71 loc) · 1.78 KB
/
parser.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
75
76
77
78
79
80
81
82
83
84
85
86
package value
import (
"bytes"
"fmt"
"strconv"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
)
type ValueParser struct {
MetricName string
DataType string
DefaultTags map[string]string
FieldName string
}
func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
vStr := string(bytes.TrimSpace(bytes.Trim(buf, "\x00")))
// unless it's a string, separate out any fields in the buffer,
// ignore anything but the last.
if v.DataType != "string" {
values := strings.Fields(vStr)
if len(values) < 1 {
return []telegraf.Metric{}, nil
}
vStr = values[len(values)-1]
}
var value interface{}
var err error
switch v.DataType {
case "", "int", "integer":
value, err = strconv.Atoi(vStr)
case "float", "long":
value, err = strconv.ParseFloat(vStr, 64)
case "str", "string":
value = vStr
case "bool", "boolean":
value, err = strconv.ParseBool(vStr)
}
if err != nil {
return nil, err
}
fields := map[string]interface{}{v.FieldName: value}
m := metric.New(v.MetricName, v.DefaultTags,
fields, time.Now().UTC())
return []telegraf.Metric{m}, nil
}
func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) {
metrics, err := v.Parse([]byte(line))
if err != nil {
return nil, err
}
if len(metrics) < 1 {
return nil, fmt.Errorf("can not parse the line: %s, for data format: value", line)
}
return metrics[0], nil
}
func (v *ValueParser) SetDefaultTags(tags map[string]string) {
v.DefaultTags = tags
}
func NewValueParser(metricName, dataType, fieldName string, defaultTags map[string]string) *ValueParser {
if fieldName == "" {
fieldName = "value"
}
return &ValueParser{
MetricName: metricName,
DataType: dataType,
DefaultTags: defaultTags,
FieldName: fieldName,
}
}