Javascript 捕获javascript console.log?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11403107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:44:01  来源:igfitidea点击:

Capturing javascript console.log?

javascript

提问by bevanb

Possible Duplicate:
Intercept calls to console.log in Chrome
Can I extend the console object (for rerouting the logging) in javascript?

可能的重复:
在 Chrome 中拦截对 console.log 的调用
我可以在 javascript 中扩展控制台对象(用于重新路由日志记录)吗?

When my JS app writes to the console.log, I want to capture that log message so that I can AJAX that log output to the server. How do I do that?

当我的 JS 应用程序写入 console.log 时,我想捕获该日志消息,以便我可以将该日志输出 AJAX 到服务器。我怎么做?

The code that writes to the log is from external services, which is why I can't just ajax it directly.

写入日志的代码来自外部服务,这就是为什么我不能直接将其ajax。

回答by Brian Nickel

You can hiHyman JavaScript functions in the following manner:

您可以通过以下方式劫持 JavaScript 函数:

(function(){
    var oldLog = console.log;
    console.log = function (message) {
        // DO MESSAGE HERE.
        oldLog.apply(console, arguments);
    };
})();
  1. Line 1wraps your function in a closure so no other functions have direct access to oldLog(for maintainability reasons).
  2. Line 2captures the original method.
  3. Line 3creates a new function.
  4. Line 4is where you send messageto your server.
  5. Line 5is invokes the original method as it would have been handled originally.
  1. 第 1行将您的函数包装在一个闭包中,因此没有其他函数可以直接访问oldLog(出于可维护性原因)。
  2. 第 2 行捕获原始方法。
  3. 第 3 行创建了一个新函数。
  4. 第 4 行是您发送message到服务器的位置。
  5. 第 5 行调用原始方法,因为它本来会被处理。

applyis used so we can invoke it onconsoleusing the original arguments. Simply calling oldLog(message)would fail because logdepends on its association with console.

apply使用这样我们就可以调用它console使用原来的参数。简单地调用oldLog(message)会失败,因为log取决于它与console.



UpdatePer zzzzBov's comment below, in IE9 console.logisn't actually a function so oldLog.applywould fail. See console.log.apply not working in IE9for more details.

更新Per zzzzBov 在下面的评论,在 IE9console.log中实际上不是一个函数,所以oldLog.apply会失败。有关更多详细信息,请参阅console.log.apply not working in IE9

回答by Tomasz Nurkiewicz

Simple:

简单的:

function yourCustomLog(msg) {
  //send msg via AJAX
}

window.console.log = yourCustomLog;

You might want to override the whole consoleobject to capture console.info, console.warnand such:

您可能想要覆盖整个console对象来 capture console.infoconsole.warn例如:

window.console = {
  log : function(msg) {...},
  info : function(msg) {...},
  warn : function(msg) {...},
  //...
}