diff --git a/lib/registry.js b/lib/registry.js index 9c9aeaf7..bf674bc0 100644 --- a/lib/registry.js +++ b/lib/registry.js @@ -305,7 +305,7 @@ function flattenSharedLabels(labels) { } function escapeLabelValue(str) { if (typeof str !== 'string') { - return str; + str = String(str); } return escapeString(str).replace(/"/g, '\\"'); } diff --git a/test/registerTest.js b/test/registerTest.js index ce4a8757..a88a7c05 100644 --- a/test/registerTest.js +++ b/test/registerTest.js @@ -340,6 +340,29 @@ describe('Register', () => { expect(escapedResult).toMatch(/\\"/); }); + it('should stringify and escape non-string label values', async () => { + register.registerMetric({ + async get() { + return { + name: 'test_metric', + type: 'counter', + help: 'A test metric', + values: [ + { + value: 12, + labels: { + label: ['say "hi"\nand \\back'], + }, + }, + ], + }; + }, + }); + + const escapedResult = await register.metrics(); + expect(escapedResult).toContain('label="say \\"hi\\"\\nand \\\\back"'); + }); + describe('should output metrics as JSON', () => { it('should output metrics as JSON', async () => { register.registerMetric(getMetric());