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
Capturing javascript console.log?
提问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);
};
})();
- Line 1wraps your function in a closure so no other functions have direct access to
oldLog
(for maintainability reasons). - Line 2captures the original method.
- Line 3creates a new function.
- Line 4is where you send
message
to your server. - Line 5is invokes the original method as it would have been handled originally.
- 第 1行将您的函数包装在一个闭包中,因此没有其他函数可以直接访问
oldLog
(出于可维护性原因)。 - 第 2 行捕获原始方法。
- 第 3 行创建了一个新函数。
- 第 4 行是您发送
message
到服务器的位置。 - 第 5 行调用原始方法,因为它本来会被处理。
apply
is used so we can invoke it onconsole
using the original arguments. Simply calling oldLog(message)
would fail because log
depends on its association with console
.
apply
使用这样我们就可以调用它在console
使用原来的参数。简单地调用oldLog(message)
会失败,因为log
取决于它与console
.
UpdatePer zzzzBov's comment below, in IE9 console.log
isn't actually a function so oldLog.apply
would 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 console
object to capture console.info
, console.warn
and such:
您可能想要覆盖整个console
对象来 capture console.info
,console.warn
例如:
window.console = {
log : function(msg) {...},
info : function(msg) {...},
warn : function(msg) {...},
//...
}