2016-03-17 17:50:39 +00:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
ejson "encoding/json"
|
2017-03-30 00:12:29 +00:00
|
|
|
"time"
|
2016-03-17 17:50:39 +00:00
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JsonSerializer struct {
|
2017-03-30 00:12:29 +00:00
|
|
|
TimestampUnits time.Duration
|
2016-03-17 17:50:39 +00:00
|
|
|
}
|
|
|
|
|
2016-11-22 12:51:57 +00:00
|
|
|
func (s *JsonSerializer) Serialize(metric telegraf.Metric) ([]byte, error) {
|
2016-03-17 17:50:39 +00:00
|
|
|
m := make(map[string]interface{})
|
2017-03-30 00:12:29 +00:00
|
|
|
units_nanoseconds := s.TimestampUnits.Nanoseconds()
|
|
|
|
// if the units passed in were less than or equal to zero,
|
|
|
|
// then serialize the timestamp in seconds (the default)
|
|
|
|
if units_nanoseconds <= 0 {
|
|
|
|
units_nanoseconds = 1000000000
|
|
|
|
}
|
2016-03-17 17:50:39 +00:00
|
|
|
m["tags"] = metric.Tags()
|
|
|
|
m["fields"] = metric.Fields()
|
|
|
|
m["name"] = metric.Name()
|
2017-03-30 00:12:29 +00:00
|
|
|
m["timestamp"] = metric.UnixNano() / units_nanoseconds
|
2016-03-17 17:50:39 +00:00
|
|
|
serialized, err := ejson.Marshal(m)
|
|
|
|
if err != nil {
|
2016-11-22 12:51:57 +00:00
|
|
|
return []byte{}, err
|
2016-03-17 17:50:39 +00:00
|
|
|
}
|
2016-11-22 12:51:57 +00:00
|
|
|
serialized = append(serialized, '\n')
|
2016-03-17 17:50:39 +00:00
|
|
|
|
2016-11-22 12:51:57 +00:00
|
|
|
return serialized, nil
|
2016-03-17 17:50:39 +00:00
|
|
|
}
|