diff --git a/src/logger.ts b/src/logger.ts index 515fa18ed..79676cd3b 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -183,9 +183,17 @@ function processData(data: Uint8Array | string, encoding?: BufferEncoding) { // strip any leading ANSI color codes from the decoded data // to parse colored JSON objects correctly decodedData = decodedData.replace(/\x1b[[(?);]{0,2}(;?\d)*./g, ''); + let parsedData; try { - return {isJSON: true, processedData: JSON.parse(decodedData)}; + parsedData = JSON.parse(decodedData); } catch (e) { return {isJSON: false, processedData: decodedData}; } + // Numbers, booleans, null and JSON strings parse successfully but they are + // not log objects, so there is nowhere to attach the context fields added by + // getJSONWithContext. Log them as plain text instead. + if (typeof parsedData !== 'object' || parsedData === null) { + return {isJSON: false, processedData: decodedData}; + } + return {isJSON: true, processedData: parsedData}; } diff --git a/test/logger.ts b/test/logger.ts index 4b9f3f062..a3e5427d2 100644 --- a/test/logger.ts +++ b/test/logger.ts @@ -86,6 +86,41 @@ describe('getModifiedData', () => { assert.equal(modifiedData, expectedJSONOutput); }); + it('json number value', () => { + const modifiedData = getModifiedData('42'); + assert.equal( + modifiedData, + JSON.stringify(Object.assign({message: '42'}, expectedMetadata)) + '\n', + ); + }); + + it('json boolean value', () => { + const modifiedData = getModifiedData('true'); + assert.equal( + modifiedData, + JSON.stringify(Object.assign({message: 'true'}, expectedMetadata)) + + '\n', + ); + }); + + it('json null value', () => { + const modifiedData = getModifiedData('null'); + assert.equal( + modifiedData, + JSON.stringify(Object.assign({message: 'null'}, expectedMetadata)) + + '\n', + ); + }); + + it('json string value', () => { + const modifiedData = getModifiedData('"abc"'); + assert.equal( + modifiedData, + JSON.stringify(Object.assign({message: '"abc"'}, expectedMetadata)) + + '\n', + ); + }); + it('json with user label', () => { const data = JSON.stringify({ text: 'default text.',