I have a utility function that wraps console.log with a condition, so we only call console.log if we're in the dev environment and console.log exists:
/* Console log if environment has debug true or #debug initially passed in URL */
metro.conlog = (function () {
return function (message) {
if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
console.log(message);
}
};
}());
This has worked very well for normal console logs. But I've recently discovered the joys of passing more than one argument to console.log: it allows you to prefix a console log with a string, so console.log('DEBUG', object)
outputs the string plus an expandable object whose properties you can inspect. How can I change my conlog function to do this? I've tried logging out all arguments like this:
metro.conlog = (function () {
return function (message) {
if ((metro.siteData.debug || metro.hashOptions.hasOwnProperty('debug')) && window.console && message) {
console.log(arguments);
}
};
}());
But this outputs the arguments as an array, instead of the neat line you get with console.log. You can see the difference in this screenshot:
Can anybody tell me how I can reproduce the original log output?
Of course you can do it, this is a demo of how to do exactly what you need, with extra options added.
And the code is below:
var mylog = (function () {
return {
log: function() {
var args = Array.prototype.slice.call(arguments);
console.log.apply(console, args);
},
warn: function() {
var args = Array.prototype.slice.call(arguments);
console.warn.apply(console, args);
},
error: function() {
var args = Array.prototype.slice.call(arguments);
console.error.apply(console, args);
}
}
}());
var name = "Alex";
var arr = [1, 2, 3];
var obj = { a:1, b:2, c:3 };
var hello = function(msg){alert(msg);};
mylog.log("Name: ", name);
mylog.log("Window Debug: ", window);
mylog.error("Some error happened");
mylog.warn("Ahh... Warning", arr, obj);
mylog.log("more parameters: ", arr, obj, hello);