Javascript - Override console.log and keep the old function

半城伤御伤魂 提交于 2019-12-19 06:38:09

问题


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


回答1:


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);
        }
    }
})();



回答2:


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;



回答3:


try this:

var console={
    log: function(v){
        alert(v);
    }
};
console.log('hello world');

UPD:

check this:

var originalConsole={
    log: (function(c){
        return function(v){
            c.log(v);
        };
    }(window.console))
};
var console={
    log: function(v){
        originalConsole.log('_original_');
        originalConsole.log(v);
    }
};
console.log('hello world');

originalConsole stores required methods of original console object(only log in my example), then console is overrided with new one.

UPD2

var console=(function(c){
    return {
        log: function(v){
            c.log('_original_');
            c.log(v);
        }
    };
}(window.console));
console.log('hello world');

I hope this will help you.




回答4:


Thanks and inspired by the answer of @Ludovic Feltz, I found an encapsulated alternative of console with custom styles.

Although this answer was not much relative to the original question, as Ludovic suggested in his comments above, I post it here in hoping to help people who also intend to customize/override console with preferred styles :)

Note: You may need to Open Your Browser Console (Press F12 by default) to see the result after clicking "Run code snippet" below.

window.msg = (function (defaultConsole) {
  return Object.assign({}, defaultConsole, {
    log(text) {
      defaultConsole.log("%cLOG: %c" + text,
        "background-color: #fff; color: #5CB85C; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #5CB85C; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    info(text) {
      defaultConsole.info("%cINFO: %c" + text,
        "background-color: #fff; color: #337AB7; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #337AB7; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    warn(text) {
      defaultConsole.warn("%cWARN: %c" + text,
        "background-color: #fff; color: #F0AD4E; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #F0AD4E; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    error(text) {
      defaultConsole.error("%cERROR: %c" + text,
        "background-color: #fff; color: #D9534F; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #D9534F; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    }
  })
}(window.console));

msg.log('Log Message !');
msg.info('Info Message !');
msg.warn('Warn Message !');
msg.error('Error Message !');
msg.debug('Debug Message !');
msg.dir('Dir Message !');

/*Note: 1).If we assign the above to console instead of msg, the default console.log, console.info, etc would be overridden with custom styles;
        2).The above methods have utilized some ES6 features which may not be compatiable with old browsers, check below for ES5 version;
*/

//The ES5 Version
window.msg2 = (function (defaultConsole) {
  //The for loop within default console is to inherit all methods from it so that the uncustomized methods like msg2.debug(), msg2.dir(), etc won't throw errors;
  for (var key in defaultConsole) {
    this[key] = defaultConsole[key];
  }
  this.log = function (text) {
    defaultConsole.log("%cLOG: %c" + text,
      "background-color: #fff; color: #5cb85c; font-weight: bold; padding-left: 8px; font-size: 1.2em",
      "background-color: #5cb85c; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
  };
  this.info = function (text) {
    defaultConsole.info("%cINFO: %c" + text,
      "background-color: #fff; color: #337ab7; font-weight: bold; padding-left: 8px; font-size: 1.2em",
      "background-color: #337ab7; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
  };
  this.warn = function (text) {
    defaultConsole.warn("%cWARN: %c" + text,
      "background-color: #fff; color: #f0ad4e; font-weight: bold; padding-left: 8px; font-size: 1.2em",
      "background-color: #f0ad4e; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
  };
  this.error = function (text) {
    defaultConsole.error("%cERROR: %c" + text,
      "background-color: #fff; color: #d9534f; font-weight: bold; padding-left: 8px; font-size: 1.2em",
      "background-color: #d9534f; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
  }
  return this;
}(window.console));

msg2.log('Log Message !');
msg2.info('Info Message !');
msg2.warn('Warn Message !');
msg2.error('Error Message !');
msg2.debug('Debug Message !');
msg2.dir('Dir Message !');


//My Original Answer is as below, which seemed simpler and more readable, however, the uncustomized methods like msg3.debug(), msg3.dir(), etc would throw errors such as 'msg3.debug is not a function';
window.msg3 = (function (defaultConsole) {
  return {
    log: function (text) {
      defaultConsole.log("%cLOG: %c" + text,
        "background-color: #fff; color: #5CB85C; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #5CB85C; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    info: function (text) {
      defaultConsole.info("%cINFO: %c" + text,
        "background-color: #fff; color: #337AB7; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #337AB7; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    warn: function (text) {
      defaultConsole.warn("%cWARN: %c" + text,
        "background-color: #fff; color: #F0AD4E; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #F0AD4E; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    },
    error: function (text) {
      defaultConsole.error("%cERROR: %c" + text,
        "background-color: #fff; color: #D9534F; font-weight: bold; padding-left: 8px; font-size: 1.2em",
        "background-color: #D9534F; color: #fff; font-weight: bold; padding: 0 8px; font-size: 1.2em");
    }
  };
}(window.console));
msg3.log('Log Message !');
msg3.info('Info Message !');
msg3.warn('Warn Message !');
msg3.error('Error Message !');
msg3.debug('Debug Message !');
msg3.dir('Dir Message !');



回答5:


You are invoking the console.log function on the window object. You should instead invoke it on the console object.

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

console.log('as');



回答6:


I would recommend using: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.

Disclaimer: I am the author of the plugin.




回答7:


One little point... console.log can receive multiple arguments, for example:

console.log('results', result1, result2, result3);

If you want this behavior, you can do something like this:

console.log = function(){
    var args = Array.from(arguments).join(' ');
    ...
}


来源:https://stackoverflow.com/questions/15657607/javascript-override-console-log-and-keep-the-old-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!