Logging nested JSON object with JSON.stringify(...) #200
|
I am trying to log a stringified JSON object using For the outermost curly braces, it is easy to double them so they are escaped for logtape. Having doubled the outermost curly braces I now get undefined for nested objects. const message = {
messageKind: "Monitor",
delta: { a: "aaa" }
}
logger.info(`message is {${JSON.stringify(message)}}`)The result is {"messageKind":"Monitor","delta":undefined}Is there a way to escape all of these curly braces? Or maybe to turn off the interpolation through a formatter option? |
Replies: 3 comments 2 replies
|
You do not need to escape the JSON. Pass it as a placeholder value instead of putting it directly into the message template: const message = {
messageKind: "Monitor",
delta: { a: "aaa" },
};
logger.info("message is {json}", {
json: JSON.stringify(message),
});The braces inside Even better, keep the object structured and let the configured formatter render it: logger.info("message is {message}", { message });Or, if you do not need a text message at all: logger.info({ message });That preserves The text formatter already knows how to render object placeholder values: it uses Doubling braces is only needed when literal braces are part of the message template itself. Moving the JSON into the properties argument avoids the escaping problem entirely. |
|
A hopefully simple followup question. The object is logged with each property as a key-value pair on a separate line. I am using the console sink + pretty formatter and though that |
|
Thanks, I'll experiment with the solutions you propose. |
You do not need to escape the JSON. Pass it as a placeholder value instead of putting it directly into the message template:
The braces inside
jsonare data, so LogTape does not parse them again. Only the first string ("message is {json}") is parsed as the message template.Even better, keep the object structured and let the configured formatter render it:
Or, if you do not need a text message at all:
That preserves
messageKindanddeltaas structured data for JSON sinks, f…