forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
66 lines (53 loc) · 1.5 KB
/
template.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
package template
import (
"strings"
"text/template"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/processors"
)
type TemplateProcessor struct {
Tag string `toml:"tag"`
Template string `toml:"template"`
Log telegraf.Logger `toml:"-"`
tmpl *template.Template
}
const sampleConfig = `
## Tag to set with the output of the template.
tag = "topic"
## Go template used to create the tag value. In order to ease TOML
## escaping requirements, you may wish to use single quotes around the
## template string.
template = '{{ .Tag "hostname" }}.{{ .Tag "level" }}'
`
func (r *TemplateProcessor) SampleConfig() string {
return sampleConfig
}
func (r *TemplateProcessor) Description() string {
return "Uses a Go template to create a new tag"
}
func (r *TemplateProcessor) Apply(in ...telegraf.Metric) []telegraf.Metric {
// for each metric in "in" array
for _, metric := range in {
var b strings.Builder
newM := TemplateMetric{metric}
// supply TemplateMetric and Template from configuration to Template.Execute
err := r.tmpl.Execute(&b, &newM)
if err != nil {
r.Log.Errorf("failed to execute template: %v", err)
continue
}
metric.AddTag(r.Tag, b.String())
}
return in
}
func (r *TemplateProcessor) Init() error {
// create template
t, err := template.New("configured_template").Parse(r.Template)
r.tmpl = t
return err
}
func init() {
processors.Add("template", func() telegraf.Processor {
return &TemplateProcessor{}
})
}