JC JC
JC JC

Reputation: 12132

Why do I get "Maximum Call Stack Size Exceeded" when I override console.log?

Here's the code..

function getMilli(){
    return new Date().getTime().toString().substr(7,6);
}
console.log = function(p1, p2, p3, p4, p5, p6){
    console.log(getMilli(), p1, p2, p3, p4, p5, p6);
}

It somehow does a "stack overflow" error but I don't get it why here.. I'm not recursively iterating things (at least I think)


...uh, yeah I was doing recursive stuff... but I didn't know how to do it. Thanks for the answers and great concepts.

Upvotes: 0

Views: 1754

Answers (3)

driangle
driangle

Reputation: 11779

You are recursively calling the function console.log. In other words, you're calling console.log within console.log.

What you probably meant to do is:

(function(){

    var clog = console.log.bind(console);

    console.log = function(p1, p2, p3, p4, p5, p6){
        clog(getMilli(), p1, p2, p3, p4, p5, p6);
    }

})();

Upvotes: 4

Ateş Göral
Ateş Göral

Reputation: 140112

As an improvement to other answers that work:

  1. Avoid polluting the global scope or the properties of any object to store the original console.log.
  2. Avoid having to specify an arbitrary number of placeholder arguments like p1, p2, p3, etc.

Use a closure to store the original console.log and also remove the dependency on arbitrary argument declarations:

console.log = function (log) {
    return function () {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(getMillis()); // Push millis as first argument
        log.apply(console, args);
    };
}(console.log);

http://jsfiddle.net/9BPuc/

Upvotes: 4

keymone
keymone

Reputation: 8104

apparently you are calling console.log from within console.log because when you reassign it to new function it does not retain link to the old one(and why should it?)

what you want to do instead is this:

console.old_log = console.log;

console.log = function() { 
  var args = Array.prototype.slice.call(arguments);
  args.unshift(getMilli()); 
  console.old_log.apply(console, args)
}

Upvotes: 1

Related Questions