SO - dynamic logging
http://stackoverflow.com/q/8494083/1011582
by dzejkej
JavaScript
var myObject = {
whatever: null,
whereever: null,
debug: false,
someFunction: function(arg) {
console.log('I am executed #1!');
},
otherFunction: function() {
console.log('I am executed #2!');
}
};
for (var key in myObject) {
// if the keys belongs to object and it is a function
if (myObject.hasOwnProperty(key) && (typeof myObject[key] === 'function')) {
// overwrite this function
myObject[key] = (function() {
// save the previous function
var functionName = key;
var functionCode = myObject[functionName];
// return new function that will write log message and run the saved function
return function() {
if (myObject.debug === true || myObject.debug === functionName) {
console.log('I am function ' + functionName + ' with arguments:', arguments);
}
functionCode(arguments);
};
})();
}
}
// debug all
myObject.debug = true;
myObject.someFunction("hello");
myObject.otherFunction(1, 3, 4);
myObject.someFunction();
// debug only someFunction()
myObject.debug = "someFunction";
myObject.someFunction("hello");
myObject.otherFunction(1, 3, 4);
myObject.someFunction();