1 |
|
2 | 'use strict';
|
3 |
|
4 | module.exports = function (config) {
|
5 | var SDC = require('statsd-client');
|
6 | var client = new SDC(config.statsd);
|
7 |
|
8 | var mappings = (config.statsd && config.statsd.mappings ? config.statsd.mappings : []).map(function (item) {
|
9 | if (item.pattern && typeof item.pattern === 'string') {
|
10 | item.pattern = new RegExp(item.pattern);
|
11 | }
|
12 | return item;
|
13 | });
|
14 |
|
15 | var methods = [
|
16 | 'timing',
|
17 | 'increment',
|
18 | 'decrement',
|
19 | 'histogram',
|
20 | 'gauge',
|
21 | 'gaugeDelta',
|
22 | 'set'
|
23 | ];
|
24 |
|
25 | var obj = {
|
26 | buildMetricNameForUrl: function (url, name) {
|
27 | if (mappings.length === 0) {
|
28 | return name;
|
29 | }
|
30 | for (var i = 0; mappings[i]; ++i) {
|
31 | if (url.match(mappings[i].pattern)) {
|
32 | return name + '_' + mappings[i].name;
|
33 | }
|
34 | }
|
35 | return name;
|
36 | }
|
37 | };
|
38 | var slice = Array.prototype.slice;
|
39 |
|
40 | var noop = function () { };
|
41 | var mock = config && config.statsd ? config.statsd.mock : true;
|
42 |
|
43 | methods.forEach(function (method) {
|
44 | var prefixedMethod = 'classified' + method.charAt(0).toUpperCase() + method.substring(1);
|
45 |
|
46 | obj[method] = (mock) ? noop : client[method].bind(client);
|
47 | obj[prefixedMethod] = (mock) ? noop : function (url, name) {
|
48 | var args = slice.call(arguments, 1);
|
49 | args[0] = obj.buildMetricNameForUrl(url, name);
|
50 | client[method].apply(client, args);
|
51 | };
|
52 | });
|
53 |
|
54 | return obj;
|
55 | };
|