Can I extend the console object (for rerouting the logging) in javascript?

Is it possible to extend the console object?

I tried something like:

Console.prototype.log = function(msg){
    Console.prototype.log.call(msg);
    alert(msg);
}

But this didn't work. I want to add additional logging to the console object via a framework like log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.

Thanks in advance!


Try following:

(function() {
    var exLog = console.log;
    console.log = function(msg) {
        exLog.apply(this, arguments);
        alert(msg);
    }
})()

You Can Also add log Time in This Way :

added Momentjs or use New Date() instead of moment.

var oldConsole = console.log;
console.log = function(){
    var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
    Array.prototype.unshift.call(arguments, timestamp);
    oldConsole.apply(this, arguments);
};

It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.

var _console={...console}

console.log = function(...args) {
    var msg = {...args}[0];
    //YOUR_CODE
    _console.log(...args);
}

// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
    if (!myclass || !myclass.verbose) // verbose switch
        return;
    var args = Array.prototype.slice.call(arguments); // toArray
    args.unshift('Verbose:');
    c.l.apply(this, args); // log
};

// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');

I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.