There’s more than one way to log a frog
Hopefully, every developer is familiar with the console log function, but who knows them all? So this time a simple post about the different log options.
console.log('I got here!!!');
=> I got here!!!
Log
After stating the obvious, here it becomes a little more interesting examples:
console.log('a', 'b', 'c');
=> abc
console.log("a",{b:'b'},"c");
=> a › {b:'b'} c
console.log("%s is for string","Bla");
=> Bla is for string
console.log("%d is for integer",3);
=> 3 is for integers
console.log("%i is for integer",4.5);
=> 4 is for integers
console.log("%f is for floating-point",4.5);
=> 4 is for integers
console.log("%o is for objects",{m:'Hi'});
=> › {m: "Hi"} is for objects
console.log("this is%c for css","color:red; font-weight: bold")
=> this is for css
console.log('%s %i %f',2.1,2.2,2.3);
=> You got the idea
Clear
To clean the console from all above.
console.clear();
Hierarchical object
console.dir({my:'object'});
=> › Object
I know, this example don’t make seance, but try this one:
let element = document.getElementById('myElId');
console.dir(element);
Interactive XML/HTML tree
console.dirxml();
If you have some interesting example, please share with me 🙁
Table view
console.table([{a:'a',b:1},{a:'a',b:2},{a:'a',b:3}]);
=> log it and see the magic...
Grouping logs
console.log('baseline');
console.group('starting');
for(i=1;i<3;i++){
console.log('I: %i',i);
console.groupCollapsed("Click to see");
for(j=1;j<2;j++){
console.log('J: %i',j);
}
console.groupEnd();
}
console.groupEnd();
console.log('done');
/// the log will look like:
baseline
› starting
I: 1
› Click to see
I: 2
› Click to see
done
Conditional logs
Print logs only if assertion fails.
console.assert(true,"You will not see this");
console.assert(false,"This will be scary red log");
=> › Assertion failed: This will be scary red log
Counter log
for(i=1;i<21;i++){
if(i%10==0){
console.count('Tens');
console.countReset('Even');
}
if(i%3==0)
console.count('Even');
}
/// the log will be like:
Even: 1
Even: 2
Even: 3
Tens: 1
Even: 1
Even: 2
Even: 3
Tens: 2
Log levels
On the browser, you will see each level in a different way, and on the setting, you can define the log level that will be displayed.
console.log('Hi');
=> Hi
console.info('Hi');
=> Hi
console.debug('Hi');
=> Hi
console.warn('Hi');
=> ! › Hi
console.error('Hi');
=> x › Hi
Time logs
console.time('overall');
for(i=1;i<3;i++){
console.time('itteration ' + i);
for(j=1;j<1000*Math.random();j++){}
console.timeEnd('itteration ' + i);
console.timeLog('overall');
}
console.timeEnd('overall');
/// the log will be like:
iitteration 1: 0.021240234375ms
overall: 2.0859375ms
itteration 2: 0.01416015625ms
overall: 2.288818359375ms
overall: 2.36083984375ms
Log the stack trace
(function foo() {
(function bar() {
console.trace();
})();
})();
// ...
console.trace
bar @ (index):37
foo @ (index):38
Conclusion: how many ways you can log a frog? Actually, there are eighteen, but who’s counting 🙂