split includeCustomLabels into customLabels and transformLabels

This commit is contained in:
Konstantin Pogorelov
2017-09-23 12:03:23 +02:00
parent 8318e0ec1d
commit a261ab76a3
2 changed files with 36 additions and 33 deletions

View File

@@ -258,10 +258,10 @@ describe('index', () => {
});
});
it('includeCustomLabels={foo: "bar"} adds foo="bar" label to metrics', done => {
it('customLabels={foo: "bar"} adds foo="bar" label to metrics', done => {
const app = express();
const instance = bundle({
includeCustomLabels: {foo: "bar"}
customLabels: {foo: 'bar'}
});
app.use(instance);
app.use('/test', (req, res) => res.send('it worked'));
@@ -279,6 +279,33 @@ describe('index', () => {
});
});
it('tarnsformLabels can set label values', done => {
const app = express();
const instance = bundle({
includePath: true,
customLabels: {foo: 'bar'},
transformLabels: labels => {
labels.foo = 'baz';
labels.path += '/ok';
}
});
app.use(instance);
app.use('/test', (req, res) => res.send('it worked'));
const agent = supertest(app);
agent
.get('/test')
.end(() => {
agent
.get('/metrics')
.end((err, res) => {
expect(res.status).toBe(200);
expect(res.text).toMatch(/foo="baz"/);
expect(res.text).toMatch(/path="\/test\/ok"/);
done();
});
});
});
it('Koa: metrics returns up=1', done => {
const app = new Koa();
const bundled = bundle({

View File

@@ -38,30 +38,6 @@ function prepareMetricNames(opts, metricTemplates) {
return names;
}
function hasCustomLabels(opts, strict){
strict = strict || false;
if (opts.hasOwnProperty('includeCustomLabels')){
let dtype;
try {
dtype = opts.includeCustomLabels.constructor.name;
} catch (e) {
dtype = opts.includeCustomLabels;
}
if (dtype === 'Object') {
return true;
}
if (strict) {
throw new Error(
'express-prom-bundle detected invalid data type for option: includeCustomLabels.\n'
+ 'Expected: Object\n'
+ 'Passed: ' + dtype
);
}
}
return false;
}
function main(opts) {
opts = Object.assign(
{
@@ -105,8 +81,8 @@ function main(opts) {
if (opts.includePath) {
labels.push('path');
}
if (hasCustomLabels(opts, true)){
labels.push.apply(labels, Object.keys(opts.includeCustomLabels));
if (opts.customLabels){
labels.push.apply(labels, Object.keys(opts.customLabels));
}
const metric = new promClient.Histogram({
name: httpMtricName,
@@ -159,11 +135,11 @@ function main(opts) {
if (opts.includePath) {
labels.path = opts.normalizePath(req, opts);
}
if (hasCustomLabels(opts, true)) {
let customLabels = opts.includeCustomLabels;
for (let key in customLabels){
labels[key] = customLabels[key];
}
if (opts.customLabels) {
Object.assign(labels, opts.customLabels);
}
if (opts.transformLabels) {
opts.transformLabels(labels, req, res);
}
timer();
});