Class: Counters::StatsD

Inherits:
Base
  • Object
show all
Defined in:
lib/counters/stats_d.rb

Constant Summary collapse

SCALING_FACTOR =

StatsD expects millisecond resolution

1_000

Instance Attribute Summary collapse

Attributes inherited from Base

#namespace

Instance Method Summary collapse

Methods inherited from Base

#hit, #latency, #magnitude, #ping

Constructor Details

#initialize(*args) ⇒ StatsD

Returns a new instance of StatsD.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/counters/stats_d.rb', line 8

def initialize(*args)
  options = args.last.is_a?(Hash) ? args.pop : Hash.new
  super(options)

  url = case args.length
        when 0
          options.fetch(:url) { raise ArgumentError, "Missing :url key from #{args.first}" }
        when 2
          "statsd://#{args.first}:#{args.last}"
        else
          raise ArgumentError, "Expected either a Hash or a host and port arguments, found: #{args.inspect}"
        end

  uri = URI.parse(url)
  @host, @port = uri.host, uri.port
  @socket = options.fetch(:socket) { UDPSocket.new }
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



6
7
8
# File 'lib/counters/stats_d.rb', line 6

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



6
7
8
# File 'lib/counters/stats_d.rb', line 6

def port
  @port
end

#socketObject (readonly)

Returns the value of attribute socket.



6
7
8
# File 'lib/counters/stats_d.rb', line 6

def socket
  @socket
end

Instance Method Details

#record_hit(key) ⇒ Object



30
31
32
# File 'lib/counters/stats_d.rb', line 30

def record_hit(key)
  socket.send("hits.#{key}:1|c", 0, host, port)
end

#record_latency(key, time_in_seconds) ⇒ Object



37
38
39
40
# File 'lib/counters/stats_d.rb', line 37

def record_latency(key, time_in_seconds)
  value = "latencies.%s:%d|ms" % [key, time_in_seconds * SCALING_FACTOR]
  socket.send(value, 0, host, port)
end

#record_magnitude(key, amount) ⇒ Object



42
43
44
45
# File 'lib/counters/stats_d.rb', line 42

def record_magnitude(key, amount)
  value = "magnitudes.%s:%d|ms" % [key, amount]
  socket.send(value, 0, host, port)
end

#record_ping(key) ⇒ Object



26
27
28
# File 'lib/counters/stats_d.rb', line 26

def record_ping(key)
  socket.send("pings.#{key}:1|c", 0, host, port)
end