Instead of having to create a custom logger for TRACE, e.g. following what methods were called and what classes were instantiated, is there an easy way to make all methods under a class log themselves? This is for a node.js application.
class MyClass
constructor: () ->
console.log 'MyClass:constructor'
doThat: () ->
console.log 'MyClass:doThat'
exports.MyClass = MyClass
myClass = new MyClass()
myClass.doThat()
If I had my way, you’d see 4 log messages instead of 2 (thus having to write less code to trace what’s happening).
I recently needed to implement something like this to trace some complicated OO-recursive stuff. Basically, i wanted to make a method “traceable” without polluting it too much; so maybe the solution could be applied here too.
First, add a function that makes other functions traceable:
Then, to use it, just add a
@tracebefore each method you want to trace:Or add @trace only once and then indent all the traceable methods one more level:
As you can see
traceis kind of abusing CoffeeScript’s syntax.method: -> 'foo'inside aclass MyClassis interpreted a method definition. But@trace method: -> 'foo'is interpreted a calling thetracefunction ofMyClass(which is aFunctioninstance, to which we’ve added thetracefunction) passing it a literal object with onemethodkey. In JavaScript it would be something likethis.trace({method: function() {return 'foo';}}).The
tracefunction will just take that object and iterate it’s keys (the method names) and values (the methods) and add functions to theMyClassprototype that log their calls and in turn call the original methods.Anyway, the output of
(new MyClass).methodA()will be:This solution doesn’t work for constructors though, as they are not just normal methods.
You can get quite fancy with this. You can also log the arguments passed to each method, the return value, and even add indentation for nested calls if you so desire (the resulting traces can then be very helpful if you need to debug a complex problem =D).
Update: as a more interesting example, here’s a mini-version of the typical composite pattern example, geometrical figures and groups of figures: http://jsfiddle.net/2YuE7/ with a more interesting tracing function. All figures understand the
movemethod. If we have this composite figure and callmoveon it:The trace output is: