Currently, when an error happens in my Node.js application, each line in the stack trace is printed in a separate log entry, as shown below:
What can I do so that, for a single error, its stack trace prints in a single log entry?
I figured out that we can customize the stack trace format using the V8 Stack Trace API: https://v8.dev/docs/stack-trace-api
So, instead of being printed as \n
separated, we can reformat it as a JSON string, so that Cloudwatch will parse it in a single log entry, like this:
Error.prepareStackTrace = (err, stack) => JSON.stringify({
message: err.message,
stack: stack.map(frame => ({
file: frame.getFileName(),
function: frame.getFunctionName(),
column: frame.getColumnNumber(),
line: frame.getLineNumber()
}))
});