Suppose I want to include some calls to console.log
for some legitimate production reason, say for something like a unit test harness. Obviously I would not want th
Paul Irish has a nice light wrapper/replacement for console.log()
.
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
Advantages:
log()
or window.log()
.Try using the code snippet below... (this is my preferred approach because it makes you independent of window.console)
var logger = (function (c) {
"use strict";
var m = {
log: function (a, t) {
if (!c) { return; /* return or call your custom function here */ }
var l = c.log,
f = t === undefined ? l : (this.__dict__[t] || l);
f.apply(c, a)
},
__dict__: {
"trace": c.trace,
"debug": c.debug,
"info": c.info,
"warn": c.warn,
"error": c.error
}
};
return {
trace: function () { m.log(arguments, "trace"); },
debug: function () { m.log(arguments, "debug"); },
info: function () { m.log(arguments, "info"); },
warn: function () { m.log(arguments, "warn"); },
error: function () { m.log(arguments, "error"); },
log: function () { m.log(arguments, undefined); }
};
}(window.console))
So you may now try these in your code and see the result
logger.info("Hello");
logger.trace("Hello");
logger.debug("Hello");
logger.warn("Hello");
logger.error("Hello");
logger.log("Hello");
As a slight variation on Chris' answer, simply define 'log' as a property of 'console' with an empty function:
if (typeof console === "undefined") {
console = {
log: function () {
return;
}
};
}
Sorry, there was a bug in my post. Don't know how I missed it.
The PROPER way to create a global console object, if it does not exist:
if (typeof console === "undefined"){
console={};
console.log = function(){
return;
}
}