Skip to content

Instantly share code, notes, and snippets.

@kimmobrunfeldt
Created April 4, 2016 11:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kimmobrunfeldt/6cdf56dde334e32304e8020ab8f5bdd6 to your computer and use it in GitHub Desktop.
Save kimmobrunfeldt/6cdf56dde334e32304e8020ab8f5bdd6 to your computer and use it in GitHub Desktop.
Monkey patching console log
console.warn('- console.(debug|info|log|warn|error) monkey-patched');
const methods = ['debug', 'info', 'log', 'warn', 'error'];
// We have to take the direct references to the actual function like this
// instead of doing just: originalConsole = console
const originalConsole = _.reduce(methods, (memo, methodName) => {
memo[methodName] = _.bind(console[methodName], console);
return memo;
}, {});
const patchedConsole = _.reduce(methods, (memo, methodName) => {
memo[methodName] = function() {
const args = Array.prototype.slice.call(arguments);
const newArgs = _.map(args, arg => {
if (Immutable.Iterable.isIterable(arg)) {
const newArg = arg.toJS();
// WARNING: DON'T ACTUALLY DO THIS. IT WILL CONFUSE
// EVERYONE.
// TODO: Do tricks to the object name so that
// users understand that magic has been applied.
return newArg;
} else {
return arg;
}
});
originalConsole[methodName].apply(this, newArgs);
}
return memo;
}, {});
// Apply monkey-patch to global.console
_.each(patchedConsole, (func, methodName) => {
console[methodName] = func;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment