Thursday, July 14, 2016

Chrome Dev Tools - Console Tricks





I’m old enough to remember debugging javascripts using alert statements littered all over the code base. However Firebug from Firefox changed the game. Nowadays I use Chrome developer tools.


Let me quickly share some less known tricks around the Chrome developer tools’ console.


1. console.log(‘message’) - This is straightforward log of a message string, nothing special.


2. How about c like string formatting of the log statement?
console.log(‘Number %d, a string %s an object %O went to a bar”, 123, “message”, { country: “Sri Lanka” })




3. Another useful way to log objects specially if it's a collection (array) is to use console.table(). Instead of having to expand and collapse individual objects to check them, you can see all of them directly in tabular form.


4. Different log levels. Just like any logging framework console has different levels of logging in addition to the console.log called info, warn and error
console.error includes a stack trace as well


5. How about printing the stack strace? This is specially useful when you want to track where an error/special condition originates from.


console.trace(“message”) will print a whole stack trace to the point at which console.trace is called.


6. Grouping logs together
It’s also possible to group a set of log statements together so you can collapse expand them and also distinguish this group from other statements.
Here’s how above works
console.group("Group starts");
console.log("Testing 1");
console.log("Testing 2");
console.log("Testing 3");
console.groupEnd();


I found this to be really useful when logging inside iterative blocks.


7. Similar to group we can use console.time() and console.timeEnd() to log the time taken to execute a set of js statements


8. Again similar to above we can use console.profile() and console.profileEnd() to add a CPU profile for further investigation. It can be seen under the ‘Profiles’ tab in dev tools


Post a Comment