Permalink
Browse files

Add an exception handling module so statsd can't disrupt the code it'…

…s monitoring.
  • Loading branch information...
1 parent 7f1c757 commit f769e3e0ea7377413ecc943cf673829f060cb968 Eric Chapweske committed Dec 18, 2011
Showing with 51 additions and 0 deletions.
  1. +24 −0 lib/statsd.rb
  2. +27 −0 spec/statsd_spec.rb
View
@@ -13,6 +13,30 @@
# statsd = Statsd.new('localhost').tap{|sd| sd.namespace = 'account'}
# statsd.increment 'activate'
class Statsd
+ # Don't raise exceptions when collection fails.
+ # If a logger is provided, the exception will be logged.
+ #
+ # @example
+ # Statsd.logger = Logger.new(STDOUT)
+ # statsd = Statsd.new
+ # statsd.extend(Statsd::ExceptionHandling)
+ module ExceptionHandling
+
+ attr_accessor :logger
+
+ def send(*args)
+ super
+ rescue Exception => exception
+ logger.error("Statsd: #{exception}") if logger
+ false
+ end
+
+ def logger
+ @logger ||= self.class.logger
+ end
+
+ end
+
# A namespace to prepend to all statsd calls.
attr_accessor :namespace
View
@@ -12,6 +12,33 @@ def socket; @socket ||= FakeUDPSocket.new end
after { @statsd.socket.clear }
+ describe "Exception handling" do
+ before do
+ @statsd.extend(Statsd::ExceptionHandling)
+ end
+
+ it "should send messages when there are no exceptions" do
+ @statsd.increment('foobar')
+ @statsd.socket.recv.must_equal ['foobar:1|c']
+ end
+
+ it "should fail silently when encountering an error on send" do
+ def @statsd.socket; raise(SocketError) end
+
+ @statsd.send('bad signature').must_equal false
+ end
+
+ it "should log the exception when a logger is provided" do
+ def @statsd.socket; raise(SocketError) end
+
+ log = StringIO.new
+ @statsd.logger = Logger.new(log)
+ @statsd.send('bad signature')
+
+ log.string.must_match 'Statsd: wrong number of arguments'
+ end
+ end
+
describe "#initialize" do
it "should set the host and port" do
@statsd.host.must_equal 'localhost'

0 comments on commit f769e3e

Please sign in to comment.