graphite.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package metrics
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net"
  6. "time"
  7. "github.com/grafana/grafana/pkg/log"
  8. "github.com/grafana/grafana/pkg/setting"
  9. )
  10. type GraphitePublisher struct {
  11. Address string
  12. Protocol string
  13. Prefix string
  14. }
  15. func CreateGraphitePublisher() (*GraphitePublisher, error) {
  16. graphiteSection, err := setting.Cfg.GetSection("metrics.graphite")
  17. if err != nil {
  18. return nil, nil
  19. }
  20. publisher := &GraphitePublisher{}
  21. publisher.Protocol = "tcp"
  22. publisher.Address = graphiteSection.Key("address").MustString("localhost:2003")
  23. publisher.Prefix = graphiteSection.Key("prefix").MustString("service.grafana.%(instance_name)s")
  24. return publisher, nil
  25. }
  26. func (this *GraphitePublisher) Publish(metrics []Metric) {
  27. conn, err := net.DialTimeout(this.Protocol, this.Address, time.Second*5)
  28. if err != nil {
  29. log.Error(3, "Metrics: GraphitePublisher: Failed to connect to %s!", err)
  30. return
  31. }
  32. buf := bytes.NewBufferString("")
  33. now := time.Now().Unix()
  34. for _, m := range metrics {
  35. metricName := this.Prefix + m.Name() + m.StringifyTags()
  36. switch metric := m.(type) {
  37. case Counter:
  38. if metric.Count() > 0 {
  39. line := fmt.Sprintf("%s %d %d\n", metricName, metric.Count(), now)
  40. buf.WriteString(line)
  41. }
  42. }
  43. }
  44. log.Trace("Metrics: GraphitePublisher.Publish() \n%s", buf)
  45. _, err = conn.Write(buf.Bytes())
  46. if err != nil {
  47. log.Error(3, "Metrics: GraphitePublisher: Failed to send metrics! %s", err)
  48. }
  49. }