How to get result of console.trace() as string in javascript with chrome or firefox?

前端 未结 8 867
情话喂你
情话喂你 2020-12-02 12:31

console.trace() outputs its result on console.
I want to get the results as string and save them to a file.

I don\'t define names for functions and

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 13:30

    This is only a minor enhancement to Konstantin's excellent code. It cuts a bit on the expense of throwing-catching and just instantiates the Error stack:

    function getStackTrace () {
        let stack = new Error().stack || '';
        stack = stack.split('\n').map(function (line) { return line.trim(); });
        return stack.splice(stack[0] == 'Error' ? 2 : 1);
    }
    

    I usually want a specific level of stack trace (for my custom logger) so this is also possible when calling:

    getStackTrace()[2]; // get stack trace info 2 levels-deep
    

提交回复
热议问题