diff --git a/lib/statsd.js b/lib/statsd.js index f27383b..893f0ed 100644 --- a/lib/statsd.js +++ b/lib/statsd.js @@ -12,9 +12,10 @@ var dgram = require('dgram'), * @option cacheDns {boolean} An optional option to only lookup the hostname -> ip address once * @option mock {boolean} An optional boolean indicating this Client is a mock object, no stats are sent. * @option global_tags {Array=} Optional tags that will be added to every metric + * @option createSocket {Function} Optional function that will be used to initialize the client's socket * @constructor */ -var Client = function (host, port, prefix, suffix, globalize, cacheDns, mock, global_tags) { +var Client = function (host, port, prefix, suffix, globalize, cacheDns, mock, global_tags, createSocket) { var options = host || {}, self = this; @@ -27,15 +28,21 @@ var Client = function (host, port, prefix, suffix, globalize, cacheDns, mock, gl globalize : globalize, cacheDns : cacheDns, mock : mock === true, - global_tags : global_tags + global_tags : global_tags, + createSocket: createSocket }; } + var createSocket = dgram.createSocket.bind(null, 'udp4'); + if (typeof options.createSocket === 'function') { + createSocket = options.createSocket; + } + this.host = options.host || 'localhost'; this.port = options.port || 8125; this.prefix = options.prefix || ''; this.suffix = options.suffix || ''; - this.socket = dgram.createSocket('udp4'); + this.socket = createSocket(); this.mock = options.mock; this.global_tags = options.global_tags || []; diff --git a/test/test_statsd.js b/test/test_statsd.js index 0fbb314..af93e00 100644 --- a/test/test_statsd.js +++ b/test/test_statsd.js @@ -178,6 +178,15 @@ describe('StatsD', function(){ assert.ok(statsd.socket instanceof dgram.Socket); }); + it('should create a socket when custom createSocket function is provided in options', function(){ + var statsd = new StatsD({ + createSocket: function() { + return 'customSocket'; + } + }); + assert.equal('customSocket', statsd.socket); + }); + }); describe('#global_tags', function(){