Jump to Real's How-to Main page

Trace the execution

This class generate a stackTrace and then parse it according to the parameters received.

[StackTrace.java]

public class StackTrace {
  public static void displayStack() {
    displayStack("", 0);
    }   
  public static void displayStack(int deep) {
    displayStack("", deep);
    }   
  public static void displayStack(String msg) {
    displayStack(msg, 0);
    }   
     
  public static void displayStack(String msg, int deep) {
    //
    //  msg      a message to appear in the Trace 
    // deep = 0  complete stack
    //    n      from "n" levels
    //
    String output = "" ;
    StringWriter sw = new StringWriter();
    new Throwable("").printStackTrace(new PrintWriter(sw));
    String stackTrace = sw.toString();
    
    // to clean up the stacktrace
    StringTokenizer st = 
      new StringTokenizer(stackTrace, "\n");
      
    // get ride of the first line
    String s=st.nextToken();
    
    // get ride of line(s) for the Trace class
    if (!msg.equals("")) output = msg + "\n" ;
    s=st.nextToken();
    s=st.nextToken();
    if ( s.indexOf("StackTrace.displayStack") < 0 ) 
        output += s + "\n";

    // process the stack        
    if (deep == 0) {
        while (st.hasMoreTokens()) {
           output += st.nextToken() + "\n";
           }
        }
    else {
        while (deep > 1) {
           if (st.hasMoreTokens()){
               output += st.nextToken() + "\n";
               deep--;
               System.out.println("**" + deep);
               }
           else
              deep = 0;
           }
        }
        
    System.out.println("Trace: " + output);
    }
}

[SimpleTrace.java]

import java.io.*;
import java.util.*;

public class SimpleTrace {
  public static void main(String args[]){
    SimpleTrace s = new SimpleTrace();
    s.doit();
    }

  public void doit() {
    MyClass s = new MyClass();
    s.aMethod();
    }
  }

class MyClass {
  MyClass() {  }
  
  public void aMethod() {
    StackTrace.displayStack("Howto Trace only 1 level", 1);
    StackTrace.displayStack("Howto Trace all levels");
    }
}

And the output should be

Trace: Howto Trace only 1 level
        at MyClass.aMethod(SimpleTrace.java:20)

Trace: Howto Trace all levels
        at MyClass.aMethod(SimpleTrace.java:21)
        at SimpleTrace.doit(SimpleTrace.java:12)
        at SimpleTrace.main(SimpleTrace.java:7)
NOTES:
The stackTrace() formatting may be different with the JVM used, in this example, it's the Sun's JDK 1.2.1.

See also this HowTo.

You may want to look at this How-to to disable the Trace mechanism in the "release" version of your classes to achieve the best performance.

Remember that line numbers are not available when a JIT is in function. To disable it, check this How-to


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]