Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2013

How to log a message in a collapsed group in Chrome DevTools Console

I have a script that produces this output in chrome devtools console:

chrome devtools console

Is it possible to log something here: (in the middle of a collapsed group)

chrome devtools console

Or here: (after all messages in a collapsed group)

chrome devtools console

After this output has been produced?

Upvotes: 7

Views: 4223

Answers (4)

Bahman.A
Bahman.A

Reputation: 1296

You can try the following for color coding your console output.

console.groupCollapsed('\x1b[36m%s\x1b[0m', `${myVar} some text`);

In this code:

  • \x1b[36m is the ANSI escape code for cyan text.
  • %s is a placeholder for the string ${myVar} some text.
  • \x1b[0m resets the color back to default after the text.

You can replace 36 with other color codes to get different colors:

  • 31: Red
  • 32: Green
  • 33: Yellow
  • 34: Blue
  • 35: Magenta
  • 36: Cyan
  • 37: White

SIDE NOTE: Please refer to the following links for details on console group methods,

Upvotes: 1

Gideon Pyzer
Gideon Pyzer

Reputation: 24028

Your output is just an example of nested console groups, so you can of course log output in-between each collapsed group as per below:

Collapsed Groups

However, I see that you are trying to modify the output AFTER it has already been logged. This is not possible as the Console API doesn't keep a reference to the objects it creates. It's therefore likely garbage collected shortly after.

I had a play to see if it was possible to override the Console API functions to implement a data store to keep track of the console logs and reference to each group. However, it seems to result in a stack overflow, so there is probably some underlying native code at play here. The solution, even if it worked, would also not modify the old output, only output a new modified version.

Upvotes: 2

Michael Warner
Michael Warner

Reputation: 4227

Doing a for in loop on the console object you will find the following methods in Chrome.

debug, error, info, log, warn, dir, dirxml, table, trace, group, groupCollapsed, groupEnd, clear, count, assert, markTimeline, profile, profileEnd, timeline, timelineEnd, time, timeEnd, timeStamp, memory

So you can do console.log, console.dir and so on.

The best ones I use are the following.

console.log -> for basic logging
console.dir -> for objects and collections
console.error -> for error messages
console.warn -> for warnings
console.table -> for data (with the correct formatting)
console.group -> when you want color coding

The best answer I can give you is try them out and see which one fits best for the situation.

Upvotes: 2

Related Questions