What is the current best way to wrap console.log() that will preserve line numbers?

Viewed 521

I've previously used the following based on other SO answers (without really understanding the need for (nor the workings of) the prototype.apply.apply

var mylogger = {
    log: function () {
        if (window.console) {
            if (window.console.log) {
                Function.prototype.apply.apply(console.log, [console, arguments]);
            }
        }
    },
    ...
};

while this prevents IE from crapping on itself, it also make the line number reporting unusable (it always reports the apply.apply.. line.

I was playing around a little and discovered that the following seems to do exactly what I need, i.e. prevent IE from crapping on itself and report the line number where mylogger.log(..) was called from..

var mylogger = {
    // function invocation returning a safe logging function..
    log: (function () {
        if (window.console && window.console.log && Function.prototype.bind) {
            return window.console.log.bind(window.console);
        } else {
            return function () {};
        }
    }()),
    ...
};

I've done some basic testing on IE/FF/Chrome without seeing any issues.. is this reasonable or is there a better way?

1 Answers
Related