Sunday, July 17, 2011

Tracing Java Applications with BTrace

BTrace is a dynamic tracing tool for Java. It allows you to insert tracing actions into the classes of a running Java program. This is especially useful, if you are using a third-party library. So, if you want to know whenever a certain method is called in your program, you can tell BTrace to print out a message whenever that method is hit. See the User Guide for more information.

Quick Start:

  • Download BTrace from here
  • Extract the release to a directory e.g. ~/btrace
  • Write a BTrace program. There are many samples present in the samples directory. Here is one of mine: the program below prints a message whenever the target program calls the ArrayList.add() method.
  • import com.sun.btrace.annotations.*;
    import static com.sun.btrace.BTraceUtils.*;
    import java.util.*;
    public class ArrayListTrace {
        // @OnMethod annotation tells where to probe.
        // In this example, we are interested in entry
        // into the ArrayList.add() method.
        // print out what was added
        public static void alert(@Self ArrayList self, Object o) {
            print("ADDED ");
  • Compile your script:
  • javac -cp "~/btrace/build/*"
  • Start the java program you want to probe and get its pid.
  • Run BTrace and watch the messages appear:
  • ~/btrace/bin/btrace -cp ".:~/btrace/build/*" <PID> ArrayListTrace.class
Useful BTrace Programs:

Here are a few useful BTrace programs I have used in the past:
  • OnThrow: Prints out the stack trace of an exception whenever a Throwable is created. This way you can capture all exceptions, even those that have been swallowed.
  • LogTracer: Prints out log messages.
  • AllMethods: Prints out the name of every method entered.

1 comment:

  1. Thank you for taking the time to write about this much needed subject. I felt that your remarks on this technology is helpful and were especially timely.

    devops course fees in chennai | devops training in chennai with placement | devops training in chennai omr | best devops training in chennai quora | devops foundation certification chennai