tags:

views:

930

answers:

4
+2  Q: 

Call trace in java

Is there a way to output a call trace for a particular thread in java?

I do not want a stack trace. I would like a sequence of calls on each object for tracing.

+2  A: 

Runtime.traceMethodCalls(), which prints a line for each method call of all objects in all threads

joe
Sun's hotspot's vm on windows does not seem to output the trace method calls. I've read i need to run java debug with 'java_g '. Any ideas?
JavaRocky
Yes, for me `Runtime.getRuntime().traceMethodCalls(true);` does nothing also. Do I need to pass arguments to `javac` or `java`?
java.is.for.desktop
+1  A: 

You'd basically want aspect-oriented programming of some form, where the aspect could determine whether the current thread was meant to be logging calls. (The alternative is to explicitly put the logging in every method yourself, which would be painful.)

There are plenty of AOP frameworks in Java, such as AspectJ and Spring (Spring is a lot more than AOP of course).

Applying aspects to every method call in the system could be tricky though... I don't have any experience with AspectJ, but Spring AOP is basically designed to enable AOP around the components. Classes which are effectively unknown to Spring can't be changed easily. Mind you, it's been a while since I've used even Spring AOP - things may have come on since then :)

Jon Skeet
A: 

We could create a new Throwable object which will have the call trace. And using some string manipulations, we can get the call stack.

Throwable t = new Throwable();
System.out.println(t.getStackTrace()[1].toString());

I'm not sure retrieving the info this way , is a good practice or not. :)

Veera
Painfully slow, so to be used for local tracing while debugging.
subtenante
+3  A: 

I think you might find this interesting. It is a java agent which adds entry and exit logging to methods, using the slf4j framework to actually log the output. Then it is a matter of configuring the logging framework to only print out that thread you are interested in.

http://www.slf4j.org/extensions.html#javaagent

(just to be explicit: 1) I wrote it, 2) it works for me :) )

Thorbjørn Ravn Andersen
WOW. Mind = Blown!
JavaRocky