UNPKG

13.4 kBMarkdownView Raw
1# hot-shots
2
3A Node.js client for [Etsy](http://etsy.com)'s [StatsD](https://github.com/etsy/statsd) server, Datadog's [DogStatsD](http://docs.datadoghq.com/guides/dogstatsd/) server, and [InfluxDB's](http://influxdb.com) [Telegraf](https://github.com/influxdb/telegraf) StatsD server.
4
5This project was originally a fork off of [node-statsd](https://github.com/sivy/node-statsd). This project
6includes all changes in the latest node-statsd and many additional changes, including:
7* TypeScript types
8* Telegraf support
9* events
10* child clients
11* tcp protocol support
12* uds (Unix domain socket) protocol support
13* raw stream protocol support
14* mock mode
15* asyncTimer
16* much more, including many bug fixes
17
18hot-shots supports Node 8.x and higher.
19
20[![Build Status](https://secure.travis-ci.org/brightcove/hot-shots.png?branch=master)](http://travis-ci.org/brightcove/hot-shots)
21
22## Migrating from node-statsd
23
24You should only need to do one thing: change node-statsd to hot-shots in all requires.
25
26You can check the detailed [change log](https://github.com/brightcove/hot-shots/blob/master/CHANGES.md) for what has changed since the last release of node-statsd.
27
28## Usage
29
30All initialization parameters are optional.
31
32Parameters (specified as one object passed into hot-shots):
33* `host`: The host to send stats to, if not set, the constructor tries to retrieve it from the `DD_AGENT_HOST` environment variable, `default: localhost`
34* `port`: The port to send stats to, if not set, the constructor tries to retrieve it from the `DD_DOGSTATSD_PORT` environment variable, `default: 8125`
35* `prefix`: What to prefix each stat name with `default: ''`
36* `suffix`: What to suffix each stat name with `default: ''`
37* `tagPrefix`: Prefix tag list with character `default: '#'`. Note does not work with `telegraf` option.
38* `tagSeparator`: Separate tags with character `default: ','`. Note does not work with `telegraf` option.
39* `globalize`: Expose this StatsD instance globally. `default: false`
40* `cacheDns`: Caches dns lookup to *host* for *cacheDnsTtl*, only used
41 when protocol is `udp`, `default: false`
42* `cacheDnsTtl`: time-to-live of dns lookups in milliseconds, when *cacheDns* is enabled. `default: 60000`
43* `mock`: Create a mock StatsD instance, sending no stats to
44 the server and allowing data to be read from mockBuffer. Note that
45 mockBuffer will keep growing, so only use for testing or clear out periodically. `default: false`
46* `globalTags`: Tags that will be added to every metric. Can be either an object or list of tags. The *Datadog* `dd.internal.entity_id` tag is appended to `globalTags` from the `DD_ENTITY_ID` environment variable if the latter is set. `default: {}`
47* `maxBufferSize`: If larger than 0, metrics will be buffered and only sent when the string length is greater than the size. `default: 0`
48* `bufferFlushInterval`: If buffering is in use, this is the time in ms to always flush any buffered metrics. `default: 1000`
49* `telegraf`: Use Telegraf's StatsD line protocol, which is slightly different than the rest `default: false`
50* `sampleRate`: Sends only a sample of data to StatsD for all StatsD methods. Can be overridden at the method level. `default: 1`
51* `errorHandler`: A function with one argument. It is called to handle various errors. `default: none`, errors are thrown/logger to console
52* `useDefaultRoute`: Use the default interface on a Linux system. Useful when running in containers
53* `protocol`: Use `tcp` option for TCP protocol, or `uds` for the Unix Domain Socket protocol or `stream` for the raw stream. Defaults to `udp` otherwise.
54* `path`: Used only when the protocol is `uds`. Defaults to `/var/run/datadog/dsd.socket`.
55* `stream`: Reference to a stream instance. Used only when the protocol is `stream`.
56* `udsGracefulErrorHandling`: Used only when the protocol is `uds`. Boolean indicating whether to handle socket errors gracefully. Defaults to true.
57* `udsGracefulRestartRateLimit`: Used only when the protocol is `uds`. Time (ms) between re-creating the socket. Defaults to `1000`.
58
59### StatsD methods
60All StatsD methods other than `event`, `close`, and `check` have the same API:
61* `name`: Stat name `required`
62* `value`: Stat value `required except in increment/decrement where it defaults to 1/-1 respectively`
63* `sampleRate`: Sends only a sample of data to StatsD `default: 1`
64* `tags`: The tags to add to metrics. Can be either an object `{ tag: "value"}` or an array of tags. `default: []`
65* `callback`: The callback to execute once the metric has been sent or buffered
66
67If an array is specified as the `name` parameter each item in that array will be sent along with the specified value.
68
69#### `close`
70The close method has the following API:
71
72* `callback`: The callback to execute once close is complete. All other calls to statsd will fail once this is called.
73
74#### `event`
75The event method has the following API:
76
77* `title`: Event title `required`
78* `text`: Event description `default is title`
79* `options`: Options for the event
80 * `date_happened` Assign a timestamp to the event `default is now`
81 * `hostname` Assign a hostname to the event.
82 * `aggregation_key` Assign an aggregation key to the event, to group it with some others.
83 * `priority` Can be ‘normal’ or ‘low’ `default: normal`
84 * `source_type_name` Assign a source type to the event.
85 * `alert_type` Can be ‘error’, ‘warning’, ‘info’ or ‘success’ `default: info`
86* `tags`: The tags to add to metrics. Can be either an object `{ tag: "value"}` or an array of tags. `default: []`
87* `callback`: The callback to execute once the metric has been sent.
88
89#### `check`
90The check method has the following API:
91
92* `name`: Check name `required`
93* `status`: Check status `required`
94* `options`: Options for the check
95 * `date_happened` Assign a timestamp to the check `default is now`
96 * `hostname` Assign a hostname to the check.
97 * `message` Assign a message to the check.
98* `tags`: The tags to add to metrics. Can be either an object `{ tag: "value"}` or an array of tags. `default: []`
99* `callback`: The callback to execute once the metric has been sent.
100
101```javascript
102 var StatsD = require('hot-shots'),
103 client = new StatsD({
104 port: 8020,
105 globalTags: { env: process.env.NODE_ENV },
106 errorHandler: errorHandler,
107 });
108
109 // Increment: Increments a stat by a value (default is 1)
110 client.increment('my_counter');
111
112 // Decrement: Decrements a stat by a value (default is -1)
113 client.decrement('my_counter');
114
115 // Histogram: send data for histogram stat (DataDog and Telegraf only)
116 client.histogram('my_histogram', 42);
117
118 // Distribution: Tracks the statistical distribution of a set of values across your infrastructure.
119 // (DataDog v6)
120 client.distribution('my_distribution', 42);
121
122 // Gauge: Gauge a stat by a specified amount
123 client.gauge('my_gauge', 123.45);
124
125 // Set: Counts unique occurrences of a stat (alias of unique)
126 client.set('my_unique', 'foobar');
127 client.unique('my_unique', 'foobarbaz');
128
129 // Event: sends the titled event (DataDog only)
130 client.event('my_title', 'description');
131
132 // Check: sends a service check (DataDog only)
133 client.check('service.up', client.CHECKS.OK, { hostname: 'host-1' }, ['foo', 'bar'])
134
135 // Incrementing multiple items
136 client.increment(['these', 'are', 'different', 'stats']);
137
138 // Incrementing with tags
139 client.increment('my_counter', ['foo', 'bar']);
140
141 // Sampling, this will sample 25% of the time the StatsD Daemon will compensate for sampling
142 client.increment('my_counter', 1, 0.25);
143
144 // Tags, this will add user-defined tags to the data
145 // (DataDog and Telegraf only)
146 client.histogram('my_histogram', 42, ['foo', 'bar']);
147
148 // Using the callback. This is the same format for the callback
149 // with all non-close calls
150 client.set(['foo', 'bar'], 42, function(error, bytes){
151 //this only gets called once after all messages have been sent
152 if(error){
153 console.error('Oh noes! There was an error:', error);
154 } else {
155 console.log('Successfully sent', bytes, 'bytes');
156 }
157 });
158
159 // Timing: sends a timing command with the specified milliseconds
160 client.timing('response_time', 42);
161
162 // Timing: also accepts a Date object of which the difference is calculated
163 client.timing('response_time', new Date());
164
165 // Timer: Returns a function that you call to record how long the first
166 // parameter takes to execute (in milliseconds) and then sends that value
167 // using 'client.timing'.
168 // The parameters after the first one (in this case 'fn')
169 // match those in 'client.timing'.
170 var fn = function(a, b) { return a + b };
171 client.timer(fn, 'fn_execution_time')(2, 2);
172
173 // Async timer: Similar to timer above, but you instead pass in a funtion
174 // that returns a Promise. And then it returns a Promise that will record the timing.
175 var fn = function () { return new Promise(function (resolve, reject) { setTimeout(resolve, n); }); };
176 var instrumented = statsd.asyncTimer(fn, 'fn_execution_time');
177 instrumented().then(function() {
178 console.log('Code run and metric sent');
179 });
180
181 // Sampling, tags and callback are optional and could be used in any combination (DataDog and Telegraf only)
182 client.histogram('my_histogram', 42, 0.25); // 25% Sample Rate
183 client.histogram('my_histogram', 42, { tag: 'value'}); // User-defined tag
184 client.histogram('my_histogram', 42, ['tag:value']); // Tags as an array
185 client.histogram('my_histogram', 42, next); // Callback
186 client.histogram('my_histogram', 42, 0.25, ['tag']);
187 client.histogram('my_histogram', 42, 0.25, next);
188 client.histogram('my_histogram', 42, { tag: 'value'}, next);
189 client.histogram('my_histogram', 42, 0.25, { tag: 'value'}, next);
190
191 // Use a child client to add more context to the client.
192 // Clients can be nested.
193 var childClient = client.childClient({
194 prefix: 'additionalPrefix.',
195 suffix: '.additionalSuffix',
196 globalTags: { globalTag1: 'forAllMetricsFromChildClient'}
197 });
198 childClient.increment('my_counter_with_more_tags');
199
200 // Close statsd. This will ensure all stats are sent and stop statsd
201 // from doing anything more.
202 client.close(function(err) {
203 console.log('The close did not work quite right: ', err);
204 });
205```
206
207## DogStatsD and Telegraf functionality
208
209Some of the functionality mentioned above is specific to DogStatsD or Telegraf. They will not do anything if you are using the regular statsd client.
210* globalTags parameter- DogStatsD or Telegraf
211* tags parameter- DogStatsD or Telegraf.
212* telegraf parameter- Telegraf
213* uds option in protocol parameter- DogStatsD
214* histogram method- DogStatsD or Telegraf
215* event method- DogStatsD
216* check method- DogStatsD
217
218## Errors
219
220As usual, callbacks will have an error as their first parameter. You can have an error in both the message and close callbacks.
221
222If the optional callback is not given, an error is thrown in some
223cases and a console.log message is used in others. An error will only
224be explicitly thrown when there is a missing callback or if it is some potential configuration issue to be fixed.
225
226If you would like to ensure all errors are caught, specify an `errorHandler` in your root
227client. This will catch errors in socket setup, sending of messages,
228and closing of the socket. If you specify an errorHandler and a callback, the callback will take precedence.
229
230```javascript
231// Using errorHandler
232var client = new StatsD({
233 errorHandler: function (error) {
234 console.log("Socket errors caught here: ", error);
235 }
236})
237```
238
239## Unix domain socket support
240
241The 'uds' option as the protocol is to support [Unix Domain Sockets for Datadog](https://docs.datadoghq.com/developers/dogstatsd/unix_socket/). It has the following limitations:
242- It only works where 'node-gyp' works. If you don't know what this is, this
243is probably fine for you. If you had an troubles with libraries that
244you 'node-gyp' before, you will have problems here as well.
245- It does not work on Windows
246
247The above will cause the underlying library that is used, unix-dgram,
248to not install properly. Given the library is listed as an
249optionalDependency, and how it's used in the codebase, this install
250failure will not cause any problems. It only means that you can't use
251the uds feature.
252
253## Submitting changes
254
255Thanks for considering making any updates to this project! Here are the steps to take in your fork:
256
2571. Run "npm install"
2582. Add your changes in your fork as well as any new tests needed
2593. Run "npm test"
2604. Update README.md with any needed documentation
2615. If you have made any API changes, update types.d.ts
2626. Push your changes and create the PR
263
264When you've done all this we're happy to try to get this merged in right away.
265
266## Package versioning and security
267
268Versions will attempt to follow semantic versioning, with major changes only coming in major versions.
269
270npm publishing is possible by one person, [bdeitte](https://github.com/bdeitte), who has two-factor authentication enabled for publishes. Publishes only contain one additional library, unix-dgram.
271
272## Name
273
274Why is this project named hot-shots? Because:
275
2761. It's impossible to find another statsd name on npm
2772. It's the name of a dumb movie
2783. No good reason
279
280## License
281
282hot-shots is licensed under the MIT license.