Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Override console.log and keep the old function

I would like to override console.log and call it on my new function.

I try something like this but I get Uncaught TypeError: Illegal invocation:

console.log = function() {
  this.apply(window, arguments);
}.bind(console.log);

console.log('as');

This is my goal:

console.error(exception); should do:

console.error = function() {
  if (typeof exception.stack !== 'undefined') {
    console.error(exception.stack);
  } else {
    console.error.apply(windows, arguments);
  }
}.bind(console.error);

console.error('as');
console.error({stack: 'my stack....'});

EDIT: Actually, it works in firefox and not in Chrome... It's a bug in Chrome: https://code.google.com/p/chromium/issues/detail?id=167911

like image 701
Charles Avatar asked Mar 27 '13 11:03

Charles


People also ask

Can you override console log?

log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method.

What can I use instead of console log?

Instead of console. log() you can also use console.info() , console. error() and console. warn() .

How do you wrap a console log?

Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .

Can you console log a function in JavaScript?

Passing a function as an argument: If the function is passed to the function console. log(), then the function will display the value of the passed function(). Output: Passing a number with message as an argument: If the number is passed to the function console.


2 Answers

You can have something like that:

console.error = (function() {
    var error = console.error;

    return function(exception) {
        if (typeof exception.stack !== 'undefined') {
            error.call(console, exception.stack);
        } else {
            error.apply(console, arguments);
        }
    }
})();
like image 191
ZER0 Avatar answered Sep 24 '22 15:09

ZER0


The best way to achieve what you want :

// define a new console
var console=(function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;
like image 27
Ludovic Feltz Avatar answered Sep 22 '22 15:09

Ludovic Feltz