Skip to content

Commit f96cbb4

Browse files
committed
Convert bool fields to int in graphite serializer
1 parent 9077cb8 commit f96cbb4

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

docs/DATA_FORMATS_OUTPUT.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ tars.cpu-total.us-east-1.cpu.usage_user 0.89 1455320690
9696
tars.cpu-total.us-east-1.cpu.usage_idle 98.09 1455320690
9797
```
9898

99-
Fields with non-numeric values will be skipped.
99+
Fields with string values will be skipped. Boolean fields will be converted
100+
to 1 (true) or 0 (false).
100101

101102
### Graphite Configuration:
102103

plugins/serializers/graphite/graphite.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,15 @@ func (s *GraphiteSerializer) Serialize(metric telegraf.Metric) ([]byte, error) {
3232
}
3333

3434
for fieldName, value := range metric.Fields() {
35-
switch value.(type) {
35+
switch v := value.(type) {
3636
case string:
3737
continue
38+
case bool:
39+
if v {
40+
value = 1
41+
} else {
42+
value = 0
43+
}
3844
}
3945
metricString := fmt.Sprintf("%s %#v %d\n",
4046
// insert "field" section of template

plugins/serializers/graphite/graphite_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,34 @@ func TestSerializeValueString(t *testing.T) {
187187
assert.Equal(t, "", mS[0])
188188
}
189189

190+
func TestSerializeValueBoolean(t *testing.T) {
191+
now := time.Now()
192+
tags := map[string]string{
193+
"host": "localhost",
194+
"cpu": "cpu0",
195+
"datacenter": "us-west-2",
196+
}
197+
fields := map[string]interface{}{
198+
"enabled": true,
199+
"disabled": false,
200+
}
201+
m, err := metric.New("cpu", tags, fields, now)
202+
assert.NoError(t, err)
203+
204+
s := GraphiteSerializer{
205+
Template: "host.field.tags.measurement",
206+
}
207+
buf, _ := s.Serialize(m)
208+
mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
209+
assert.NoError(t, err)
210+
211+
expS := []string{
212+
fmt.Sprintf("localhost.enabled.cpu0.us-west-2.cpu 1 %d", now.Unix()),
213+
fmt.Sprintf("localhost.disabled.cpu0.us-west-2.cpu 0 %d", now.Unix()),
214+
}
215+
assert.Equal(t, expS, mS)
216+
}
217+
190218
// test that fields with spaces get fixed.
191219
func TestSerializeFieldWithSpaces(t *testing.T) {
192220
now := time.Now()

0 commit comments

Comments
 (0)