Skip to content

Instantly share code, notes, and snippets.

@jbgutierrez
Created April 3, 2012 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbgutierrez/2290409 to your computer and use it in GitHub Desktop.
Save jbgutierrez/2290409 to your computer and use it in GitHub Desktop.
Idea para contextualizar las llamadas a console.log
var AClass = new Class({
Implements: [ExtendedLogger],
initialize: function() {
this.initLogger('AClass', {
skip: ['silentMethod'],
debug: true
});
this.silentMethod();
this.otherMethod();
},
silentMethod: function() {
this.log("Esto no sale en el log");
},
otherMethod: function() {
this.log("Esto sí sale en el log");
}
});
var ExtendedLogger =
(function(){
var stacks = [];
new Class({
stack: [],
initLogger: function(name, options) {
stacks.push(this.stack);
if (options == null) {
options = {};
}
var skip = options['skip'] || [];
skip.combine(['log', '_log', 'initLogger', 'addEvent', 'removeEvent', 'fireEvent']);
var debug = options['debug'];
var self = this;
var properties = Object.keys(self.$constructor.prototype);
properties.each(function(property) {
var oldDefinition = self[property];
if (skip.contains(property)) {
return;
}
if (oldDefinition instanceof Function) {
var newDefinition = function() {
if (debug) {
self._log(name + "." + property + ":", '+', 1, arguments);
}
self.stack.push(property);
var start = new Date().getTime();
var result = oldDefinition.apply(self, arguments);
var end = new Date().getTime();
var time = end - start;
if (debug) {
self._log(name + "." + property + ": " + time + "ms", '-');
}
self.stack.pop(property);
return result;
};
self[property] = newDefinition;
}
});
this.log = function(omsg) {
this._log(" " + omsg + " [" + name + "." + (self.stack.getLast() || 'anonymous') + "]");
};
this._log = function(msg, separator, offset, arg) {
if (separator == null) {
separator = ' ';
}
if (offset == null) {
offset = 0;
}
if (arg == null) {
arg = '';
}
if (debug) {
var indentLevel = stacks.reduce((function(a, b) {
return a + b.length;
}), 0);
var indent = ' '.repeat(indentLevel + offset - 1);
if (separator === ' ') {
indent += separator;
} else {
indent += ' ' + separator;
}
console.log("" + indent + " " + msg, arg);
} else {
console.log(msg);
}
};
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment