Constructing a Lightweight Generic Function Trace Mechanism for Javascript

(I’ve brought together the ideas for this concept from various places – thanks to this answer on Stack Overflow and in turn this page for information about arguments.callee).

Oftentimes, when you’re constructing a complex Javascript application, it can be very useful to add tracing to it so that you can track the execution flow – when methods are called, and with which arguments. This is especially important when trying to debug later on. The Javascript arguments array can be used to help do this. However, the arguments array isn’t a real array – it has some quirks. I’ve spent some time experimenting, and I’ve come up with a generic tracing function that you can use. Crucially, the line to invoke it is just copy and paste, no modification is needed. This means you can easily paste it throughout your code without tiresome pasting in of function names or arguments.

The generic trace function looks like this:

function trace(argumentsArray, calleeItem) {
    var functionName = calleeItem.match(/function\s+(\w+)\s*\(/)[1];
    console.debug("Entered function " + functionName + " with arguments", argumentsArray);
}

You can use it simply by inserting the following line into the header of each function you write:

trace(Array.prototype.slice.call(arguments), arguments.callee.toString());

That line looks complex, but it does not need to be modified for each function you write. The first parameter copies the arguments array into a real, mutable array that can be passed into the trace function. The second takes the callee (i.e. the function being traced) and passes it into the trace function (which then strips off the function prefix).

For example, you might write some code like this:

function sayHello(firstname, surname) {
    trace(Array.prototype.slice.call(arguments), arguments.callee.toString());

    console.info("Hello, " + firstname + " " + surname + "!");
}

sayHello("John", "Smith");

That would produce output in your console that looks like:

Entered function sayHello with arguments ["John", "Smith"]
Hello, John Smith!

Any suggestions for improvements to this idea gladly welcomed!