In firebase, I am trying to log some JSON objects in a human readable format but it either prints as an [object] or escaped when stringified. no middle ground. it appears in the same way on the Logs Dashboard. for example,
const data = {
event: 'my-event',
value: 'foo-bar-baz',
};
functions.logger.log(`data = ${data}`);
functions.logger.log(`dataStringified = ${JSON.stringify(data)}`);
prints as
> {"severity":"INFO","message":"data = [object Object]"}
> {"severity":"INFO","message":"data2 = {\"event\":\"my-event\",\"value\":\"foo-bar-baz\"}"}
What am I doing wrong?
CodePudding user response:
You are not doing anything wrong, the message object payload is a string of "data2 = {\"event\":\"my-event\",\"value\":\"foo-bar-baz\"}"
so in order to show the key value pairs in their default state (using double quotes), the double quotes within the actual message need to be escaped otherwise, the message value would be terminated early by showing another double quote symbol and you would get output that looks like: "data2 = {"
. What you could do to make it more human readable is replace the double quotes that stringified gives you with single quotes. Something like this should do it:
functions.logger.log(`dataStringified = ${JSON.stringify(data).replaceAll('"',"'")}`);
I ran this locally using my emulator and recieved the following output:
{
"severity": "INFO",
"message": "dataStringified = {'event':'my-event','value':'foo-bar-baz'}"
}