Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log js stack trace with console.trace() but keep it collapsed

I wanted to log the stack trace for certain function calls in my app. I like the way console.trace() present the data, but it always spits it out to console expanded. if you have dozens of logs this gets messy very quickly.

Some people suggested using log Error().stack, others console.error(), others Error.captureStackTrace(). But all of these had things I did not like. console.error clutters the console and makes it hard to see real errors. the others did not print out as nice or useable stacks.

There should be a way to simply get console.trace() to default to collapsed.

like image 652
user1768699 Avatar asked Oct 01 '18 16:10

user1768699


2 Answers

The answer was to use console.groupCollapsed();

    console.groupCollapsed('name to show to identify trace');
    console.log('additional data hidden inside collapsed group');
    console.trace(); // hidden in collapsed group
    console.groupEnd();

Which looks something like this in console. ( works in chrome, not sure of others )

enter image description here

like image 170
user1768699 Avatar answered Nov 15 '22 17:11

user1768699


console.error might work for you instead.

It shows all logs collapsed.

screenshot with console.error

console.trace

Here are the same logs, but with trace. They are expanded by default.

enter image description here

Don't worry about the two seemingly different expanded variations of the logs in the .error call. They look identical for the same collapsed or expanded state with both .trace and .error calls.

You may be concerned about the log level filtering with this, which would be a valid concern. For that, I can only suggest that you prepend your logs with a unique searchable string to filter it out or in.

like image 26
Jayant Bhawal Avatar answered Nov 15 '22 17:11

Jayant Bhawal