Javascript - Override console.log and keep the old function

前端 未结 8 1171
春和景丽
春和景丽 2021-01-12 08:49

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:

相关标签:
8条回答
  • 2021-01-12 09:18

    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);
            }
        }
    })();
    
    0 讨论(0)
  • 2021-01-12 09:21

    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 !');

    0 讨论(0)
  • 2021-01-12 09:22

    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.

    0 讨论(0)
  • 2021-01-12 09:28

    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;
    
    0 讨论(0)
  • 2021-01-12 09:37

    Just enhancing the previous answer of @Ludovic to make his answer also support nodejs:

    // 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
            }
        };
    }(global.console !== undefined ? global.console : window.console));
    
    0 讨论(0)
  • 2021-01-12 09:38

    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(' ');
        ...
    }
    
    0 讨论(0)
提交回复
热议问题