32

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.

user1768699
  • 1,041
  • 9
  • 8

2 Answers2

57

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

Leonel
  • 825
  • 11
  • 19
user1768699
  • 1,041
  • 9
  • 8
  • 2
    This is a good solution, but there is a problem that the group cannot be filtered out by levels (error, warn, info, verbose) and texts in Filter text box. This issue is described here: https://stackoverflow.com/questions/38620729/google-chrome-console-filter-out-groups – Tomoyuki Aota Apr 13 '19 at 13:22
  • Wow... Just wow... – Vitalii Korsakov Dec 28 '22 at 12:19
3

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.

Jayant Bhawal
  • 2,044
  • 2
  • 31
  • 32