1 | require 'socket'
|
2 | require 'yaml'
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | class Statsd
|
27 |
|
28 | def self.timing(stats, time, sample_rate=1)
|
29 | Statsd.update_stats(stats, time, sample_rate, 'ms')
|
30 | end
|
31 |
|
32 | def self.increment(stats, sample_rate=1)
|
33 | Statsd.update_stats(stats, 1, sample_rate)
|
34 | end
|
35 |
|
36 | def self.decrement(stats, sample_rate=1)
|
37 | Statsd.update_stats(stats, -1, sample_rate)
|
38 | end
|
39 |
|
40 | def self.gauges(stats, value, sample_rate=1)
|
41 | Statsd.update_stats(stats, value, sample_rate, 'g')
|
42 | end
|
43 |
|
44 | def self.sets(stats, value, sample_rate=1)
|
45 | Statsd.update_stats(stats, value, sample_rate, 's')
|
46 | end
|
47 |
|
48 | def self.update_stats(stats, delta=1, sample_rate=1, metric='c')
|
49 | stats = [stats].flatten
|
50 |
|
51 | data = {}
|
52 | stats.each do |stat|
|
53 | data[stat] = "%s|%s" % [delta, metric]
|
54 | end
|
55 |
|
56 | Statsd.send(data, sample_rate)
|
57 | end
|
58 |
|
59 | def self.send(data, sample_rate=1)
|
60 | begin
|
61 | host = config["host"] || "localhost"
|
62 | port = config["port"] || "8125"
|
63 |
|
64 | sampled_data = {}
|
65 | if sample_rate < 1
|
66 | if rand <= sample_rate
|
67 | data.each_pair do |stat, val|
|
68 | sampled_data[stat] = "%s|@%s" % [val, sample_rate]
|
69 | end
|
70 | end
|
71 | else
|
72 | sampled_data = data
|
73 | end
|
74 |
|
75 | udp = UDPSocket.new
|
76 | sampled_data.each_pair do |stat, val|
|
77 | send_data = "%s:%s" % [stat, val]
|
78 | udp.send send_data, 0, host, port
|
79 | end
|
80 | udp.close
|
81 | rescue => e
|
82 | puts e.message
|
83 | end
|
84 | end
|
85 |
|
86 | def self.config
|
87 | return @@config if self.class_variable_defined?(:@@config)
|
88 | begin
|
89 | config_path = File.join(File.dirname(__FILE__), "statsd.yml")
|
90 |
|
91 | if defined? Rails
|
92 | config_path = File.join(Rails.root, "config", "statsd.yml")
|
93 | @@config = open(config_path) { |f| YAML.load(f) }
|
94 | @@config = @@config[Rails.env]
|
95 | else
|
96 | @@config = open(config_path) { |f| YAML.load(f) }
|
97 | end
|
98 | rescue => e
|
99 | puts "config: #{e.message}"
|
100 | @@config = {}
|
101 | end
|
102 |
|
103 | @@config
|
104 | end
|
105 | end
|