I would like to instrument Javascript code in order to "log" values of global variables. For example I would like to know all the values a particular variables foo had during execution. The logging is not the problem. Do any of you know what would be the easiest way to implement this? I was thinking of using Rhino (the Javascript implementation in Java created by Mozilla) to generate an AST and modifying this AST.
Firebug (plugin for firefox) has a logging feature, to which you can write to a console. Much better than using alert("foo"); for everything
example log statement:
console.log("foo="+foo);
See this post for more info (including more advanced usage)
I have no idea for a generic solution or anything that exists, but simply wrap those variables around a logging class that deals with get/sets and stuff.
You can set debugger; as first thing on the document ready event and just step through your code step by step.
..fredrik
This may be what you are looking for:
http://ejohn.org/blog/javascript-getters-and-setters/
put a log in the setter and that's it. Of course, I do not know where does this actually works, if it must be trusted code, or any web page, or what.
based on John Resig's code, I would add to my debug code something like:
var placeLoggerInSetter = function(variableName, obj){ //obj may be window
obj.__defineSetter__(variableName, function(val){
console.log(val); //log whatever here
obj[variableName] = val;
});
}
var something = 0;
placeLoggerInSetter("something", window);
something = 1;
//out goes "1" in the console
something = 2
//out goes "2" in the console
Is that more like it? Again, I did not test it and the obj[variableName] line looks quite recursive to me... will you tell here if it works? :)
Also, with firebug:
console.dir(obj)
will let you see all the properties of that object in the console, instead of converting it to string as with log(). And also expand the properties and so on. Handy.
If you're not restricted to Rhino/Java, the Johnson Ruby gem integrates the Spidermonkey/Tracemonkey interpreter into Ruby. It does provide access to the AST. I haven't tried modifying the AST; not sure if that's possible (it might be, judging from the names in the code at looked at).
The Johnson gem is in jbarnette's Johnson repo at github. (Switch id's; Stackoverflow doesn't want me to put links in at this point ...) I added tracemonkey support recently and it's not yet integrated into the master source. It's in my (smparkes)'s Johnson repo at github.
Using the cvshead version of Rhino, I instrumented the code.