Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 925
thebjorn Avatar asked Dec 28 '13 19:12

thebjorn


1 Answers

What you're doing is fine I guess, but if you aren't adding any additional functionality, you could do something simple and in one line:

window.console = (window.console || {debug:function(){},log:function(){},error:function(){}});

You could, of course, add other console functions if you use them.

like image 128
Jordan Kasper Avatar answered Oct 06 '22 00:10

Jordan Kasper