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.*;
    @BTrace
    public class ArrayListTrace {
    
        // @OnMethod annotation tells where to probe.
        // In this example, we are interested in entry
        // into the ArrayList.add() method.
        @OnMethod(
            clazz="java.util.ArrayList",
            method="add";
        )
        // print out what was added
        public static void alert(@Self ArrayList self, Object o) {
            print("ADDED ");
            println(o);
        }
    }
    
  • Compile your script:
  • javac -cp "~/btrace/build/*" ArrayListTrace.java
    
  • 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. This post is really informative; it has helped me understand so many things. Definitely I will share this article within my circle. So, thank you for sharing with us.
    Java Training in Chennai
    Java Course in Chennai

    ReplyDelete