Javascript log function
Prevent errors on console methods when no console present and expose a global 'log' function.
HTML
Press 'Run' and check your console!
<hr />
Source at: <a href='https://gist.github.com/bgrins/5108712'>https://gist.github.com/bgrins/5108712</a>
JavaScript
var logr = {};
// Full version of `log` that:
// * Prevents errors on console methods when no console present.
// * Exposes a global 'log' function that preserves line numbering and formatting.
(function () {
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
logr.log = Function.prototype.bind.call(function() {
var args = ['ADVISED'].concat(Array.prototype.slice.call(arguments))
Function.prototype.apply.call(console.log, console, args);
}, console);
console.logr = Function.prototype.bind.call(function() {
var args = ['ADVISED'].concat(Array.prototype.slice.call(arguments))
Function.prototype.apply.call(console.log, console, args);
}, console);
})();
function Test() {}
Test.prototype.extraMethod = function() { }
Test.methodAttachedToFunction = function(withParam) { }
log("A single string");
log(123);
log(["An", "Array", "Of", "Strings"]);
log("The %s jumped over %d tall buildings", "person", 100);
log("The", "person", "jumped over ", 100, " tall buildings");
log("The object %o is inspectable!", { person: { jumpedOver: [100, "tall buildings"]}});
log('%cThis is red text on a green background', 'color:red; background-color:green');
log({ an: "obj", withNested: { objects:...