I am creating a Javascript logger, in which, on error messages, I am also adding the stack trace like this:
function logMessage(logMessage)
{
let stackTrace = new Error().stack;
logMessage.stackTrace = stackTrace;
...
}
This gives me the stack trace, but it also obviously adds the method of logMessage
itself as the last item on the stack...
How can I remove the last trace so I'll only see the trace up until the point that the logMessage
was called, but without the logMessage
itself?
The way to do it is really simple since the stack we are getting is a string divided by \n
, in this format:
ERROR \n
at ... \n
at ... \n
so all we need to do is:
let stackTrace = new Error().stack; //get the stack trace string
let arr = stackTrace.split("\n"); //create an array with all lines
arr.splice(1,1); //remove the second line (first line after "ERROR")
stackTrace = arr.join("\n"); //join array back to a string