UNPKG

2.69 kBPlain TextView Raw
1require 'socket'
2require 'yaml'
3
4# ruby_example.rb
5
6# Ian Sefferman <iseff@iseff.com>
7# http://www.iseff.com
8
9# If this is running in a Rails environment, will pick up config/statsd.yml.
10# config/statsd.yml should look like:
11# production:
12# host: statsd.domain.com
13# port: 8125
14# development:
15# host: localhost
16# port: 8125
17
18# If this file is not running in Rails environment, will pick up ./statsd.yml
19# ./statsd.yml should look like:
20# host: localhost
21# port: 8125
22
23# If neither of these files are present, it will default to localhost:8125
24
25# Sends statistics to the stats daemon over UDP
26class 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 # for Rails environments, check Rails.root/config/statsd.yml
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
105end