forked from mixmaxhq/cloudwatch-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
244 lines (232 loc) · 7.93 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/**
* This module provides a simplified wrapper for creating and publishing
* CloudWatch metrics. We should always initialize our environment first:
*
* ```
* var cloudwatchMetrics = require('cloudwatch-metrics');
* cloudwatchMetrics.initialize({
* region: 'us-east-1'
* });
* ```
*
* For creating a metric, we simply need to provide the
* namespace and the type of metric:
*
* ```
* var myMetric = new cloudwatchMetrics.Metric('namespace', 'Count');
* ```
*
* If we want to add our own default dimensions, such as environment information,
* we can add it in the following manner:
*
* ```
* var myMetric = new cloudwatchMetrics.Metric('namespace', 'Count', [{
* Name: 'environment',
* Value: 'PROD'
* }]);
* ```
*
* If we want to disable a metric in certain environments (such as local development),
* we can make the metric in the following manner:
*
* ```
* // isLocal is a boolean
* var isLocal = someWayOfDetermingIfLocal();
*
* var myMetric = new cloudwatchMetrics.Metric('namespace', 'Count', [{
* Name: 'environment',
* Value: 'PROD'
* }], {
* enabled: isLocal
* });
* ```
*
* Then, whenever we want to publish a metric, we simply do:
*
* ```
* myMetric.put(value, metric, additionalDimensions);
* ```
*
* Be aware that the `put` call does not actually send the metric to CloudWatch
* at that moment. Instead, it stores unsent metrics and sends them to
* CloudWatch on a predetermined interval (to help get around sending too many
* metrics at once - CloudWatch limits you by default to 150 put-metric data
* calls per second). The default interval is 5 seconds, if you want metrics
* sent at a different interval, then provide that option when construction your
* CloudWatch Metric:
*
* ```
* var myMetric = new cloudwatchMetrics.Metric('namespace', 'Count', [{
* Name: 'environment',
* Value: 'PROD'
* }], {
* sendInterval: 3 * 1000 // It's specified in milliseconds.
* });
* ```
*
* You can also register a callback to be called when we actually send metrics
* to CloudWatch - this can be useful for logging put-metric-data errors:
* ```
* var myMetric = new cloudwatchMetrics.Metric('namespace', 'Count', [{
* Name: 'environment',
* Value: 'PROD'
* }], {
* sendCallback: (err) => {
* if (!err) return;
* // Do your error handling here.
* }
* });
* ```
*/
var AWS = require('aws-sdk');
var _ = require('underscore');
var _awsConfig = {region: 'us-east-1'};
/**
* setIndividialConfig sets the default configuration to use when creating AWS
* metrics. It defaults to simply setting the AWS region to `us-east-1`, i.e.:
*
* {
* region: 'us-east-1'
* }
* @param {Object} config The AWS SDK configuration options one would like to set.
*/
function initialize(config) {
_awsConfig = config;
}
const DEFAULT_METRIC_OPTIONS = {
enabled: true,
sendInterval: 5000,
sendCallback: () => {},
maxCapacity: 20
};
//see http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html
const UNITS = {
"SECONDS" : "Seconds",
"MICROSECONDS" : "Microseconds",
"MILLISECONDS" : "Milliseconds",
"BYTES" : "Bytes",
"KILOBYTES" : "Kilobytes",
"MEGABYTES": "Megabytes" ,
"GIGABYTES" : "Gigabytes",
"TERABYTES" : "Terabytes",
"BITS" : "Bits",
"KILOBITS" : "Kilobits",
"MEGABITS" : "Megabits",
"GIGABITS" : "Gigabits",
"TERABITS" : "Terabits",
"PERCENT" : "Percent",
"COUNT" : "Count",
"BYTESSECOND" : "Bytes/Second",
"KILOBYTESSECOND" : "Kilobytes/Second",
"MEGABYTESSECOND" : "Megabytes/Second",
"GIGABYTESSECOND" : "Gigabytes/Second",
"TERABYTESSECOND" : "Terabytes/Second",
"BITSSECOND" : "Bits/Second",
"KILOBITSSECOND" : "Kilobits/Second",
"MEGABITSSECOND" : "Megabits/Second",
"GIGABITSSECOND" : "Gigabits/Second",
"TERABITSSECOND" : "Terabits/Second",
"COUNTSECOND" : "Count/Second",
"NONE": "None"
};
/**
* Create a custom CloudWatch Metric object that sets pre-configured dimensions and allows for
* customized metricName and units. Each CloudWatchMetric object has it's own internal
* AWS.CloudWatch object to prevent errors due to overlapping callings to
* AWS.CloudWatch#putMetricData.
*
* @param {String} namespace CloudWatch namespace
* @param {String} units CloudWatch units
* @param {Object} defaultDimensions (optional) Any default dimensions we'd
* like the metric to have.
* @param {Object} options (optional) Options used to control metric
* behavior.
* @param {Bool} options.enabled Defaults to true, controls whether we
* publish the metric when `Metric#put()` is called - this is useful for
* turning off metrics in specific environments.
*/
function Metric(namespace, units, defaultDimensions, options) {
var self = this;
self.cloudwatch = new AWS.CloudWatch(_awsConfig);
self.namespace = namespace;
self.units = units;
self.defaultDimensions = defaultDimensions || [];
self.options = _.defaults(options || {}, DEFAULT_METRIC_OPTIONS);
self._storedMetrics = [];
if (self.options.enabled) {
const UNIT_VALS = _.values(UNITS);
if(!_.contains(UNIT_VALS, units)) {
throw 'cloudwatch-metrics: Unrecognized unit';
}
self._interval = setInterval(() => {
self._sendMetrics();
}, self.options.sendInterval);
}
}
/**
* Publish this data to Cloudwatch
* @param {Integer|Long} value Data point to submit
* @param {String} namespace Name of the metric
* @param {Array} additionalDimensions Array of additional CloudWatch metric dimensions. See
* http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html for details.
*/
Metric.prototype.put = function(value, metricName, additionalDimensions) {
var self = this;
// Only publish if we are enabled
if (self.options.enabled) {
additionalDimensions = additionalDimensions || [];
self._storedMetrics.push({
MetricName: metricName,
Dimensions: self.defaultDimensions.concat(additionalDimensions),
Unit: self.units,
Value: value
});
// We need to see if we're at our maxCapacity, if we are - then send the
// metrics now.
if (self._storedMetrics.length === self.options.maxCapacity) {
clearInterval(self._interval);
self._sendMetrics();
self._interval = setInterval(() => {
self._sendMetrics();
}, self.options.sendInterval);
}
}
};
/**
* Samples a metric so that we send the metric to Cloudwatch at the given
* sampleRate.
* @param {Integer|Long} value Data point to submit
* @param {String} namespace Name of the metric
* @param {Array} additionalDimensions Array of additional CloudWatch metric dimensions. See
* http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html for details.
* @param {Float} sampleRate The rate at which to sample the metric at.
* The sample rate must be between 0.0 an 1.0. As an example, if you provide
* a sampleRate of 0.1, then we will send the metric to Cloudwatch 10% of the
* time.
*/
Metric.prototype.sample = function(value, metricName, additionalDimensions, sampleRate) {
if (Math.random() < sampleRate) this.put(value, metricName, additionalDimensions);
};
/**
* _sendMetrics is called on a specified interval (defaults to 5 seconds but
* can be overridden but providing a `sendInterval` option when creating a
* Metric). It is what actually sends metrics to CloudWatch. It passes the
* sendCallback option (if provided) as the callback to the put-metric-data
* call. This can be useful for logging AWS errors.
*/
Metric.prototype._sendMetrics = function() {
var self = this;
// NOTE: this would be racy except that NodeJS is single threaded.
const dataPoints = self._storedMetrics;
self._storedMetrics = [];
if (_.isEmpty(dataPoints)) return;
self.cloudwatch.putMetricData({
MetricData: dataPoints,
Namespace: self.namespace
}, self.options.sendCallback);
};
module.exports = {
initialize,
Metric,
UNITS
};