fix bypass test, minor change to docs, move bypass logic after serving the /metrics route, see MR #70

This commit is contained in:
Konstantin Pogorelov
2020-11-29 15:46:19 +01:00
parent bffb4cf16e
commit 0205d4cfc8
3 changed files with 25 additions and 13 deletions

View File

@@ -52,7 +52,7 @@ Which labels to include in `http_request_duration_seconds` metric:
* **includeUp**: include an auxiliary "up"-metric which always returns 1, default: **true**
* **metricsPath**: replace the `/metrics` route with a **regex** or exact **string**. Note: it is highly recommended to just stick to the default
* **metricType**: histogram/summary selection. See more details below
* **bypass**: Function which takes express request as an argument. Determines whether the given request should be included in the metrics or not, default: **() => false**
* **bypass**: function taking express request as an argument and determines whether the given request should be excluded in the metrics, default: **() => false**
### metricType option ###

View File

@@ -204,12 +204,15 @@ describe('index', () => {
const app = express();
const instance = bundle({
bypass: (req)=> {
return ['/test', /bad.word/].includes(req.url)
// metrics added here to attempt skipping /metrics
// this should fail though, because serving /metrics preceeds bypassing
return !!req.url.match(/test|bad.word|metrics/)
}
});
app.use(instance);
app.use('/test', (req, res) => res.send('it worked'));
app.use('/some/bad-word', (req, res) => res.send('it worked too'));
app.use('/good-word', (req, res) => res.send('this will be counted'));
const agent = supertest(app);
agent
.get('/test')
@@ -217,14 +220,21 @@ describe('index', () => {
agent
.get('/some/bad-word')
.end(() => {
const metricHashMap = instance.metrics.http_request_duration_seconds.hashMap;
expect(metricHashMap['status_code:200']).not.toBeDefined();
agent
.get('/metrics')
.end((err, res) => {
expect(res.status).toBe(200);
done();
.get('/good-word')
.end(() => {
const metricHashMap = instance.metrics.http_request_duration_seconds.hashMap;
expect(metricHashMap['status_code:200']).toBeDefined();
// only /good-word should be counted
expect(metricHashMap['status_code:200'].count).toBe(1);
agent
.get('/metrics')
.end((err, res) => {
expect(res.status).toBe(200);
done();
});
});
});
});

View File

@@ -131,16 +131,18 @@ function main(opts) {
: new RegExp('^' + (opts.metricsPath || '/metrics') + '/?$');
const middleware = function (req, res, next) {
if (opts.bypass && opts.bypass(req)) {
return next();
}
const path = req.originalUrl || req.url; // originalUrl gets lost in koa-connect?
if (opts.autoregister && path.match(metricsMatch)) {
return metricsMiddleware(req, res);
}
// bypass() is checked only after /metrics was processed
// if you wish to disable /metrics use autoregister:false instead
if (opts.bypass && opts.bypass(req)) {
return next();
}
if (opts.excludeRoutes && matchVsRegExps(path, opts.excludeRoutes)) {
return next();
}