-
Notifications
You must be signed in to change notification settings - Fork 67
/
index.js
179 lines (155 loc) · 5.13 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
const onFinished = require('on-finished');
const promClient = require('prom-client');
const normalizePath = require('./normalizePath');
const normalizeStatusCode = require('./normalizeStatusCode');
function matchVsRegExps(element, regexps) {
for (const regexp of regexps) {
if (regexp instanceof RegExp) {
if (element.match(regexp)) {
return true;
}
} else if (element === regexp) {
return true;
}
}
return false;
}
function clusterMetrics() {
const aggregatorRegistry = new promClient.AggregatorRegistry();
const metricsMiddleware = function(req, res) {
aggregatorRegistry.clusterMetrics((err, clusterMetrics) => {
if (err) {
console.error(err);
return res.sendStatus(500);
}
res.set('Content-Type', aggregatorRegistry.contentType);
res.send(clusterMetrics);
});
};
return metricsMiddleware;
}
function main(opts) {
if (arguments[2] && arguments[1] && arguments[1].send) {
arguments[1].status(500)
.send('<h1>500 Error</h1>\n'
+ '<p>Unexpected 3rd param in express-prom-bundle.\n'
+ '<p>Did you just put express-prom-bundle into app.use '
+ 'without calling it as a function first?');
return;
}
opts = Object.assign(
{
autoregister: true,
includeStatusCode: true,
normalizePath: main.normalizePath,
formatStatusCode: main.normalizeStatusCode,
metricType: 'histogram',
promClient: {}
}, opts
);
if (opts.prefix
|| opts.keepDefaultMetrics !== undefined
|| opts.whitelist !== undefined
|| opts.blacklist !== undefined
) {
throw new Error(
'express-prom-bundle detected one of the obsolete options: '
+ 'prefix, keepDefaultMetrics, whitelist, blacklist. '
+ 'Please refer to oficial docs. '
+ 'Most likely you upgraded the module without the necessary code changes'
);
}
if (opts.promClient.collectDefaultMetrics) {
promClient.collectDefaultMetrics(opts.promClient.collectDefaultMetrics);
}
const httpMetricName = opts.httpDurationMetricName || 'http_request_duration_seconds';
function makeHttpMetric() {
const labels = ['status_code'];
if (opts.includeMethod) {
labels.push('method');
}
if (opts.includePath) {
labels.push('path');
}
if (opts.customLabels) {
labels.push.apply(labels, Object.keys(opts.customLabels));
}
if (opts.metricType === 'summary') {
return new promClient.Summary({
name: httpMetricName,
help: 'duration summary of http responses labeled with: ' + labels.join(', '),
labelNames: labels,
percentiles: opts.percentiles || [0.5, 0.75, 0.95, 0.98, 0.99, 0.999],
maxAgeSeconds: opts.maxAgeSeconds,
ageBuckets: opts.ageBuckets
});
} else if (opts.metricType === 'histogram' || !opts.metricType) {
return new promClient.Histogram({
name: httpMetricName,
help: 'duration histogram of http responses labeled with: ' + labels.join(', '),
labelNames: labels,
buckets: opts.buckets || [0.003, 0.03, 0.1, 0.3, 1.5, 10]
});
} else {
throw new Error('metricType option must be histogram or summary');
}
}
const metrics = {
[httpMetricName]: makeHttpMetric()
};
if (opts.includeUp !== false) {
metrics.up = new promClient.Gauge({
name: 'up',
help: '1 = up, 0 = not up'
});
metrics.up.set(1);
}
const metricsMiddleware = function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(promClient.register.metrics());
};
const metricsMatch = opts.metricsPath instanceof RegExp ? opts.metricsPath
: new RegExp('^' + (opts.metricsPath || '/metrics') + '/?$');
const middleware = function (req, res, next) {
const path = req.originalUrl || req.url; // originalUrl gets lost in koa-connect?
if (opts.autoregister && path.match(metricsMatch)) {
return metricsMiddleware(req, res);
}
if (opts.excludeRoutes && matchVsRegExps(path, opts.excludeRoutes)) {
return next();
}
const labels = {};
const timer = metrics[httpMetricName].startTimer(labels);
onFinished(res, () => {
if (opts.includeStatusCode) {
labels.status_code = opts.formatStatusCode(res, opts);
}
if (opts.includeMethod) {
labels.method = req.method;
}
if (opts.includePath) {
labels.path = opts.normalizePath instanceof Function
? opts.normalizePath(req, opts)
: main.normalizePath(req, opts);
}
if (opts.customLabels) {
Object.assign(labels, opts.customLabels);
}
if (opts.transformLabels) {
opts.transformLabels(labels, req, res);
}
timer();
});
next();
};
middleware.metrics = metrics;
middleware.promClient = promClient;
middleware.metricsMiddleware = metricsMiddleware;
return middleware;
}
// this is kept only for compatibility with the code relying on older version
main.promClient = promClient;
main.normalizePath = normalizePath;
main.normalizeStatusCode = normalizeStatusCode;
main.clusterMetrics = clusterMetrics;
module.exports = main;