16

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.

JavaRocky
  • 19,203
  • 31
  • 89
  • 110

8 Answers8

14

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
  • 73,784
  • 33
  • 194
  • 347
11

There is btrace, that can be used for this kind of action.

Smar
  • 8,109
  • 3
  • 36
  • 48
4

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
  • 32,532
  • 36
  • 98
  • 137
4

If you want to trace the execution of your Java code you can use a tool called InTrace.

NOTE: InTrace is a free and open source tool which I have written.

mchr
  • 6,161
  • 6
  • 52
  • 74
2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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

laalto
  • 150,114
  • 66
  • 286
  • 303
joe
  • 34,529
  • 29
  • 100
  • 137
1

The more easier way than Btrace is using HouseMD, you can get the from here

zhongl
  • 11
  • 2
0

If you're using IntelliJ, there is plugin called Flameviewer. Please find more details on the below link,

https://github.com/kornilova-l/FlameViewer#uploading-file-to-flameviewer

parrotjack
  • 432
  • 1
  • 6
  • 18