The console
object gives you access to the browser’s console. It lets you output strings, arrays, and objects that help debug your code. The console
is part of the window
object, and is supplied by the Browser Object Model (BOM)
There are two ways how to use console.log:
window.console.log('hello')
console.log('hello again')
You may want a simple way to:
DEBUG = true
$ 23.07.2018 / 11:48:02 Hello!
log("Hello!")
e.g. We want to add the current date before the message:
var LOG_PREFIX = new Date().getDate() + '.' + new Date().getMonth() + '.' + new Date().getFullYear() + ' / ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds();
var log = console.log;
console.log = function(){
// 1. Convert args to a normal array
var args = Array.from(arguments);
// OR you can use: Array.prototype.slice.call( arguments );
// 2. Prepend log prefix log string
args.unshift(LOG_PREFIX + ": ");
// 3. Pass along arguments to console.log
log.apply(console, args);
}
console.log('I did it!')
Current date:
var LOG_PREFIX = new Date().getDate() + '.' + new Date().getMonth() + '.' + new Date().getFullYear() + ' / ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds();
Save object reference
var log = console.log;
Rewrite the log method
console.log = function(){
var args = Array.from(arguments); // ES5
args.unshift(LOG_PREFIX + ": ");
log.apply(console, args);
}
arguments
object is not an Array
. It is similar to an Array
, but does not have any Array
properties except length
. You can also use: Array.prototype.slice.call(arguments);apply
is what this
will refer to. To mimic a call to console.log()
, you have to pass console
, not the function itselfYou may want to modify the log messages and use shorter logging syntax:
var LOG_PREFIX = new Date().getDate() + '.' + new Date().getMonth() + '.' + new Date().getFullYear() + ' / ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds();
var log = function(){
// 1. Convert args to a normal array
var args = Array.prototype.slice.call(arguments);
// 2. Prepend log prefix log string
args.unshift(LOG_PREFIX + " ");
// 3. Pass along arguments to console.log
console.log.apply(console, args);
}
log('I did it!')
The most basic log wrap to exactly mimic console.log
behavior, e.g., to shorten logging syntax, looks like the following, which applies the arguments supplied to log
when calling console.log
.
var log = function(){
console.log.apply(console, arguments);
}
And you can do simple things like add a DEBUG
flag to enable/disable logging:
var DEBUG=true;
var log = function(){
if(DEBUG){
console.log.apply(console, arguments);
}
}
Thanks for reading!
#javascript #js #frontend #webdev #development