Skip to content

Commit

Permalink
implementation to Handle where a string is passed to the logger that …
Browse files Browse the repository at this point in the history
…happens to be JSON, with new lines in it #1
  • Loading branch information
hiro5id committed Dec 11, 2019
1 parent 2add326 commit 6efdb9c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,21 @@ export function FormatErrorObject(object: any) {
returnData.message = returnData.message.substring(3);
}

if (returnData.message.length === 0 && returnData.level === 'error') {
// interpret JSON if it is inside the error message
if (returnData.message && returnData.message.length > 0) {
let parsedObject = null;
try {
parsedObject = JSON.parse(returnData.message);
} catch (err) {
// do nothing
}
if (parsedObject != null) {
returnData.message = '<auto-parsed-json-string-see-@autoParsedJson-property>';
returnData['@autoParsedJson'] = parsedObject;
}
}

if (returnData.message != null && returnData.message.length === 0 && returnData.level === 'error') {
returnData.message = '<no-error-message-was-passed-to-console-log>';
}

Expand Down
50 changes: 50 additions & 0 deletions test/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,56 @@ describe('logger', () => {
expect(JSON.parse(outputText[0]).circ.circ).eql("[Circular ~.circ]");
});

it('Handle where a string is passed to the logger that happens to be JSON, with new lines in it', async () => {
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole();

const circObject: any = {bob:"bob"};
circObject.circ = circObject;

const sampleStringJson = `
{
"attachments": [
{
"color": "#0062FF",
"fields": [
{
"title": "# of SDs for READY state update",
"value": "56"
},
{
"title": "PDF_VERIFIED => READY",
"value": "56"
}
],
"author_name": "DSP Conversion Runner"
},
{
"color": "#DA1E28",
"fields": [
{
"title": "# of SDs failed to update state",
"value": "0"
}
],
"author_name": "DSP Conversion Runner"
}
]
}
`;

console.log(sampleStringJson);

restoreStdOut(originalWrite);
LoggerRestoreConsole();

console.log(outputText[0]);

expect(JSON.parse(outputText[0]).level).eql("info");
expect(JSON.parse(outputText[0])["@autoParsedJson"]).eql({"attachments":[{"color":"#0062FF","fields":[{"title":"# of SDs for READY state update","value":"56"},{"title":"PDF_VERIFIED => READY","value":"56"}],"author_name":"DSP Conversion Runner"},{"color":"#DA1E28","fields":[{"title":"# of SDs failed to update state","value":"0"}],"author_name":"DSP Conversion Runner"}]});
});


it('console.log logs as info when explicitly provided with level:info parameter', async () => {
const {originalWrite, outputText} = overrideStdOut();
LoggerAdaptToConsole();
Expand Down

0 comments on commit 6efdb9c

Please sign in to comment.