2020-02-06 20:40:03 +00:00
|
|
|
package template
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"text/template"
|
2020-02-06 21:34:36 +00:00
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
"github.com/influxdata/telegraf/plugins/processors"
|
2020-02-06 20:40:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type TemplateProcessor struct {
|
2020-02-06 21:34:36 +00:00
|
|
|
Tag string `toml:"tag"`
|
|
|
|
Template string `toml:"template"`
|
|
|
|
Log telegraf.Logger `toml:"-"`
|
2020-02-06 20:40:03 +00:00
|
|
|
tmpl *template.Template
|
|
|
|
}
|
|
|
|
|
|
|
|
const sampleConfig = `
|
2020-02-06 21:34:36 +00:00
|
|
|
## 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" }}'
|
2020-02-06 20:40:03 +00:00
|
|
|
`
|
|
|
|
|
|
|
|
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 {
|
2020-02-06 21:34:36 +00:00
|
|
|
r.Log.Errorf("failed to execute template: %v", err)
|
|
|
|
continue
|
2020-02-06 20:40:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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() {
|
2020-02-06 21:34:36 +00:00
|
|
|
processors.Add("template", func() telegraf.Processor {
|
2020-02-06 20:40:03 +00:00
|
|
|
return &TemplateProcessor{}
|
|
|
|
})
|
|
|
|
}
|