diff --git a/lib/registry.js b/lib/registry.js index 9ba0194f..a07c68f2 100644 --- a/lib/registry.js +++ b/lib/registry.js @@ -2,6 +2,22 @@ const { getValueAsString } = require('./util'); +const ESCAPE_STRING_REPLACE_MAP = { + '\\': '\\\\', + '\n': '\\n', +}; + +const ESCAPE_LABEL_VALUE_REPLACE_MAP = { + ...ESCAPE_STRING_REPLACE_MAP, + '"': '\\\\"', +}; + +const ESCAPE_REPLACE_REGEXP = /\\|\n|"/g; + +function REPLACE_FUNC(dict) { + return char => dict[char] || ''; +} + class Registry { static get PROMETHEUS_CONTENT_TYPE() { return 'text/plain; version=0.0.4; charset=utf-8'; @@ -234,10 +250,15 @@ function escapeLabelValue(str) { if (typeof str !== 'string') { return str; } - return escapeString(str).replace(/"/g, '\\"'); + + return escapeString(str, ESCAPE_LABEL_VALUE_REPLACE_MAP); } -function escapeString(str) { - return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); +function escapeString(str, extraReplaceDict) { + const fullDict = extraReplaceDict + ? extraReplaceDict + : ESCAPE_STRING_REPLACE_MAP; + + return str.replace(ESCAPE_REPLACE_REGEXP, REPLACE_FUNC(fullDict)); } function standardizeCounterName(name) { return name.replace(/_total$/, '');