timing.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package event
  2. import "fmt"
  3. // Timing keeps min/max/avg information about a timer over a certain interval
  4. type Timing struct {
  5. Name string
  6. Min int64
  7. Max int64
  8. Value int64
  9. Count int64
  10. }
  11. // NewTiming is a factory for a Timing event, setting the Count to 1 to prevent div_by_0 errors
  12. func NewTiming(k string, delta int64) *Timing {
  13. return &Timing{Name: k, Min: delta, Max: delta, Value: delta, Count: 1}
  14. }
  15. // Update the event with metrics coming from a new one of the same type and with the same key
  16. func (e *Timing) Update(e2 Event) error {
  17. if e.Type() != e2.Type() {
  18. return fmt.Errorf("statsd event type conflict: %s vs %s ", e.String(), e2.String())
  19. }
  20. p := e2.Payload().(map[string]int64)
  21. e.Count += p["cnt"]
  22. e.Value += p["val"]
  23. e.Min = minInt64(e.Min, p["min"])
  24. e.Max = maxInt64(e.Max, p["max"])
  25. return nil
  26. }
  27. // Payload returns the aggregated value for this event
  28. func (e Timing) Payload() interface{} {
  29. return map[string]int64{
  30. "min": e.Min,
  31. "max": e.Max,
  32. "val": e.Value,
  33. "cnt": e.Count,
  34. }
  35. }
  36. // Stats returns an array of StatsD events as they travel over UDP
  37. func (e Timing) Stats() []string {
  38. return []string{
  39. fmt.Sprintf("%s.count:%d|c", e.Name, e.Count),
  40. fmt.Sprintf("%s.avg:%d|ms", e.Name, int64(e.Value/e.Count)), // make sure e.Count != 0
  41. fmt.Sprintf("%s.min:%d|ms", e.Name, e.Min),
  42. fmt.Sprintf("%s.max:%d|ms", e.Name, e.Max),
  43. }
  44. }
  45. // Key returns the name of this metric
  46. func (e Timing) Key() string {
  47. return e.Name
  48. }
  49. // SetKey sets the name of this metric
  50. func (e *Timing) SetKey(key string) {
  51. e.Name = key
  52. }
  53. // Type returns an integer identifier for this type of metric
  54. func (e Timing) Type() int {
  55. return EventTiming
  56. }
  57. // TypeString returns a name for this type of metric
  58. func (e Timing) TypeString() string {
  59. return "Timing"
  60. }
  61. // String returns a debug-friendly representation of this metric
  62. func (e Timing) String() string {
  63. return fmt.Sprintf("{Type: %s, Key: %s, Value: %+v}", e.TypeString(), e.Name, e.Payload())
  64. }
  65. func minInt64(v1, v2 int64) int64 {
  66. if v1 <= v2 {
  67. return v1
  68. }
  69. return v2
  70. }
  71. func maxInt64(v1, v2 int64) int64 {
  72. if v1 >= v2 {
  73. return v1
  74. }
  75. return v2
  76. }