Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

wrap statsd._send in try..catch so client apps don't die because of s…

…ocket errors
  • Loading branch information...
commit c7fdd2bfd44bd37b87e24f5682e7115a0b7ca44f 1 parent 760cc2d
@vgod vgod authored
Showing with 24 additions and 11 deletions.
  1. +16 −11 statsd.py
  2. +8 −0 statsd_test.py
View
27 statsd.py
@@ -7,6 +7,7 @@
import random
from socket import socket, AF_INET, SOCK_DGRAM
import time
+import logging
__version__ = '1.0.3'
@@ -61,20 +62,23 @@ def gauge(self, bucket, value, sample_rate=None):
def _send(self, bucket, value, sample_rate=None):
"""Format and send data to statsd.
"""
- bucket = bucket if isinstance(bucket, bytes) else bucket.encode('utf8')
+ try:
+ bucket = bucket if isinstance(bucket, bytes) else bucket.encode('utf8')
- sample_rate = sample_rate or self._sample_rate
- if sample_rate and sample_rate < 1.0 and sample_rate > 0:
- if random.random() <= sample_rate:
- value = value + b'|@' + str(sample_rate).encode('utf8')
- else:
- return
+ sample_rate = sample_rate or self._sample_rate
+ if sample_rate and sample_rate < 1.0 and sample_rate > 0:
+ if random.random() <= sample_rate:
+ value = value + b'|@' + str(sample_rate).encode('utf8')
+ else:
+ return
- stat = bucket + b':' + value
- if self._prefix:
- stat = self._prefix + b'.' + stat
+ stat = bucket + b':' + value
+ if self._prefix:
+ stat = self._prefix + b'.' + stat
- self._socket.sendto(stat, (self._host, self._port))
+ self._socket.sendto(stat, (self._host, self._port))
+ except Exception,e:
+ _logger.error("Failed to send statsd packet.", exc_info=True)
def timing(self, bucket, ms, sample_rate=None):
"""Creates a timing sample.
@@ -174,4 +178,5 @@ def init_statsd(settings=None):
sample_rate=STATSD_SAMPLE_RATE, prefix=STATSD_BUCKET_PREFIX)
return _statsd
+_logger = logging.getLogger('statsd')
_statsd = init_statsd()
View
8 statsd_test.py
@@ -42,6 +42,14 @@ def test_init_statsd(self):
self.assertEqual(statsd.STATSD_SAMPLE_RATE, 0.99)
self.assertEqual(statsd.STATSD_BUCKET_PREFIX, 'testing')
+ def test_exception_in_send(self):
+ def mock_sendto_raise_error(data, addr):
+ mock_sendto_raise_error.exception_raised = True
+ raise socket.gaierror
+ statsd._statsd._socket.sendto = mock_sendto_raise_error
+ statsd.decrement('counted')
+ self.assertTrue(mock_sendto_raise_error.exception_raised)
+
def test_decrement(self):
statsd.decrement('counted')
self.assertEqual(statsd._statsd._socket.data, b'counted:-1|c')
Please sign in to comment.
Something went wrong with that request. Please try again.