【问题标题】:Javascript - Override console.log and keep the old functionJavascript - 覆盖 console.log 并保留旧功能
【发布时间】:2023-03-28 06:54:02
【问题描述】:

我想覆盖 console.log 并在我的新函数上调用它。

我尝试这样的事情,但我得到了Uncaught TypeError: Illegal invocation

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

console.log('as');

这是我的目标:

console.error(exception); 应该这样做:

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....'});

编辑: 实际上,它适用于 Firefox 而不是 Chrome... 这是 Chrome 中的一个错误:https://code.google.com/p/chromium/issues/detail?id=167911

【问题讨论】:

  • 很难说你的目标是什么。你想在调用console.log时调用不同的函数,以及调用原来的console.log吗?
  • 我编辑添加了我的目标。

标签: javascript console overriding


【解决方案1】:

你可以有这样的东西:

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

【讨论】:

  • :) 我只是调整你的代码,如果你在拥有typeof exception.stack之前检查exception实际上是一个对象而不是null会更好,否则你可以有一些例外。
【解决方案2】:

实现您想要的最佳方式:

// 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;

【讨论】:

  • 点赞!刚刚尝试了以下内容: var msg=(function(oldCons){ return { log: function(text){ oldCons.log('%c' + text,"color:#00DFB9;background-color: #032320; font-大小:2em;字体粗细:粗体;填充:4px 6px;"); } }; }(window.console)); msg.log('Hello World!'); console.log('Hello World !');
  • 您应该发布您的代码作为答案,它可能对某些人有所帮助。它没有正确格式化为评论。
  • 嗯,谢谢你的好意提醒,我上面的评论主要是为了感谢你,这启发了我实现一个带有自定义样式的控制台的封装替代方案,但是与原始样式相比并没有太大问题...
  • 谢谢 :) 即使与原始问题无关,您仍然可以展示您所做的事情,以便未来寻找自定义风格化控制台的人可以复制和编辑您的。也许赞成它:)顺便说一句,当我做出这个答案时,我没有想到这种用途;)
  • 根据您的建议,我在下面发布了一个新答案,谢谢兄弟:)
【解决方案3】:

感谢并受到@Ludovic Feltz 回答的启发,我找到了一个带有自定义样式的控制台的封装替代方案。

虽然这个答案与原来的问题没有太大关系,正如 Ludovic 在上面的 cmets 中所建议的那样,我在这里发布它是为了帮助那些也打算用首选样式自定义/覆盖控制台的人:)

注意:您可能需要打开您的浏览器控制台(默认按 F12)单击下面的“运行代码 sn-p”后才能看到结果。

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

【讨论】:

    【解决方案4】:

    您正在对 window 对象调用 console.log 函数。您应该改为在 console 对象上调用它。

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

    【讨论】:

      【解决方案5】:

      试试这个:

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

      UPD:

      检查一下:

      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 存储原始console 对象的所需方法(在我的示例中只有log),然后console 被新对象覆盖。

      UPD2

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

      希望对你有帮助。

      【讨论】:

      • 谢谢,但我不想要警报,我想在控制台中打印。
      • @charles:好的,所以你想用新的替换原来的console,并从新的调用原始的。对吗?
      • 谢谢我这样做了,但我想避免使用另一个变量...我认为这是不可能的..
      • @charles:我看到你已经选择了最好的 anwser,但是无论如何:))请参阅我的帖子中的 upd2。可以避免额外的变量。 javascript 创造奇迹 :) 原始 console 可通过函数内的 c var 访问。对于外部世界,console 是你想要的任何东西 :) 干杯!
      • 谢谢,但是您的解决方案覆盖了整个console,因此console.error 不再起作用。我试试这个:pastebin.com/qFiwGsBD 但我仍然得到非法调用......
      【解决方案6】:

      我建议使用:https://github.com/sunnykgupta/jsLogger

      特点:

      1. 它安全地覆盖了 console.log。
      2. 请注意控制台是否不可用(哦,是的,您也需要考虑这一点。)
      3. 存储所有日志(即使它们被禁止)以供以后检索。
      4. 处理主要的控制台功能,如logwarnerrorinfo

      开放修改,并会在有新建议出现时更新。

      免责声明:我是插件的作者。

      【讨论】:

        【解决方案7】:

        一点点...console.log可以接收多个参数,例如:

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

        如果你想要这种行为,你可以这样做:

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

        【讨论】:

          【解决方案8】:

          只是增强了@Ludovic之前的回答,让他的回答也支持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));
          

          【讨论】:

            猜你喜欢
            • 2016-06-03
            • 2010-09-14
            • 2012-03-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-16
            相关资源
            最近更新 更多