How to get Javascript Function Calls/Trace at Runt

2019-01-31 07:11发布

问题:

As I interact with my AJAX based application at RUNTIME I'd like the console to spit out all the functions it's calling. (so no stack trace, or breakpoints, or profiling or anything)

So for example, let's say I pressed a button on the page. I'd like for it to return all the functions it went through when that happened:

So I'd see in the console something like (when I pressed a button):

1. button1Clicked();
2.     calculating();
3.          printingResults();

Which basically means that button1Clicked() called calculating() which called printingResults()

Is there a utility, or plugin, browser, or maybe some way in the language to do this? I'm using google chrome, btw.

p.s and NO I do not want to go through each function and add a "console.log("inside function X")" b/c that's too much work

p.p.s as an added bonus I'd like to see the arguments passed into the functions too, but maybe that's pushing it. :>

回答1:

I can't think of a great way to intercept all function calls globally to insert logging (though there is a decent workaround in the update section below).

Instead, how about only adding logging to functions in a certain namespace that you care about? You can do this with the following setup code:

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

Then, for whatever namespaceObject you want to add logging to, you just call:

functionLogger.addLoggingToNamespace(yourNamespaceObject);

Here's a fiddle to see it in action.

UPDATE
Note that you can call functionLogger.addLoggingToNamespace(window); to add logging to all global functions at the time of the call. Also, if you really want, you can traverse the tree to find any functions and update them accordingly. The one downfall of this method is that it only works on functions that exist at the time. Thus, it's still not the greatest solution, but it's a LOT less work than adding logging statements by hand :)



回答2:

This is called profiling and Chrome and Firebug have it built in. In Chrome developer Tools, go to the profiles tab and click the record (circle) button. Perform your ajax and after your response, click the record button again to stop. The results of the profiling will appear in the right pane.

Note, this is going to give you everything so if you are using a library like jQuery, the vast majority of the function calls are going to be garbage to you. I've tried this a few times and I find it is much more helpful to do the console.log('inside <method>') thing.



回答3:

Maybe you can have JavaScript do some of the work of adding console.log for you:

Adding console.log to every function automatically

Also this blog by Paul Irish might help:

http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

It includes a link to some JavaScript specifically targeted at logging arguments:

http://pastie.org/1033665



回答4:

Give a try to diyism_trace_for_javascript.htm:

https://code.google.com/p/diyism-trace/downloads/list

eval('window.c=function(){3+5;}');
declare_ticks_for(window);

function a(k, c) {
  return k + 2;
}

function b() {
  4 + 3;
  a(3, {'a':'c','b':'d'});
  c();
  return 5 + 4;
}

b();

View logs in console tab of chrome or firefox



回答5:

A variation on Briguy37's solution, I wrote one that accepts a function to call before each method. It also works with ECMAScript 6 classes, where methods are not enumerated by for...in. I'm using it to modify Object prototypes, to add logging to all new instances of my object.

function inject(obj, beforeFn) {
    for (let propName of Object.getOwnPropertyNames(obj)) {
        let prop = obj[propName];
        if (Object.prototype.toString.call(prop) === '[object Function]') {
            obj[propName] = (function(fnName) {
                return function() {
                    beforeFn.call(this, fnName, arguments);
                    return prop.apply(this, arguments);
                }
            })(propName);
        }
    }
}

function logFnCall(name, args) {
    let s = name + '(';
    for (let i = 0; i < args.length; i++) {
        if (i > 0)
            s += ', ';
        s += String(args[i]);
    }
    s += ')';
    console.log(s);
}

inject(Foo.prototype, logFnCall);


回答6:

I've used @Briguy37's solution with an improvement. In my case, I did not want to trace functions from some libraries, so I added some code to exclude them. Here is how it is used:

  • First, include the definition of the functions you don't want to trace;
  • excludeLoggingToNamespace to list the functions defined up to now and exclude them;
  • Include the definition of the functions you want to trace;
  • Call addLoggingToNamespace to add the logging capability to the functions defined in the above step.

Example:

<script src="js/someLibrary.js"></script>
<script>
    functionLogger.excludeLoggingToNamespace(window);
</script>
<script src="js/codeIWantToTraceHere.js"></script>
<script>
    functionLogger.addLoggingToNamespace(window);
</script>

Here is the code I added to @Briguy37's solution:

var excludedFunctions = {};

        functionLogger.excludeLoggingToNamespace = function(namespaceObject){
            for(var name in namespaceObject){
                var potentialFunction = namespaceObject[name];

                if(Object.prototype.toString.call(potentialFunction) === '[object Function]') {
                    excludedFunctions[name] = name;
                }
            }
        }; 

And I had to modify @Briguy37's addLoggingToNamespace method to take into accound the excludedFunctions hash:

functionLogger.addLoggingToNamespace = function(namespaceObject){
    for(var name in namespaceObject){
        var potentialFunction = namespaceObject[name];

        if(Object.prototype.toString.call(potentialFunction) === '[object Function]' && 
           !excludedFunctions[name]) {
            namespaceObject[name] = functionLogger.getLoggableFunction(potentialFunction, name);
        }
    }
};