在运行时与基于AJAX的应用程序进行交互时,我希望控制台吐出它正在调用的所有功能。 (因此没有堆栈跟踪,断点,配置文件或其他任何内容)
例如,假设我按下了页面上的一个按钮。我希望它返回所有功能
经历了什么时候发生的:
因此,我会在控制台中看到类似的内容(当我按下按钮时):
1. button1Clicked();
2. calculating();
3. printingResults();
这基本上意味着button1Clicked()称为Calculation(),其称为printingResults()
是否有实用程序,插件,浏览器,或者某种语言可以做到这一点?我正在使用谷歌浏览器,顺便说一句。
p.s和否,我不想遍历每个函数并添加一个
"console.log("inside function X")"
b/c太多的工作p.p.s作为一个额外的好处,我也希望看到参数也传递到函数中,但这也许正在插入它。 :>
最佳答案
我想不出一种全局拦截所有函数调用以插入日志记录的好方法(尽管下面的更新部分有不错的解决方法)。
相反,仅将日志记录添加到您关心的某个命名空间中的函数怎么样?您可以使用以下安装代码执行此操作:
var functionLogger = {};
functionLogger.log = true;//Set this to false to disable logging
/**
* Gets a function that when called will log information about itself if logging is turned on.
*
* @param func The function to add logging to.
* @param name The name of the function.
*
* @return A function that will perform logging and then call the function.
*/
functionLogger.getLoggableFunction = function(func, name) {
return function() {
if (functionLogger.log) {
var logText = name + '(';
for (var i = 0; i < arguments.length; i++) {
if (i > 0) {
logText += ', ';
}
logText += arguments[i];
}
logText += ');';
console.log(logText);
}
return func.apply(this, arguments);
}
};
/**
* After this is called, all direct children of the provided namespace object that are
* functions will log their name as well as the values of the parameters passed in.
*
* @param namespaceObject The object whose child functions you'd like to add logging to.
*/
functionLogger.addLoggingToNamespace = function(namespaceObject){
for(var name in namespaceObject){
var potentialFunction = namespaceObject[name];
if(Object.prototype.toString.call(potentialFunction) === '[object Function]'){
namespaceObject[name] = functionLogger.getLoggableFunction(potentialFunction, name);
}
}
};
然后,对于要添加日志记录的任何namespaceObject,只需调用:
functionLogger.addLoggingToNamespace(yourNamespaceObject);
Here's a fiddle观看它的运行。
更新
请注意,您可以在调用时调用
functionLogger.addLoggingToNamespace(window);
将日志添加到所有全局函数。另外,如果您确实需要,可以遍历树以查找任何功能并相应地更新它们。这种方法的一个缺点是它仅适用于当时存在的功能。因此,它仍然不是最大的解决方案,但是比手工添加日志记录语句要少很多的工作:)