title: getting stacktrace with context to thread
body: <p>I am trying to get the current stack-trace of a Thread in Java.  I have explored the following methods:</p>
  
  <ol>
  <li><p>One of the easiest way of printing stack trace of current thread in Java is by using dumpStack()  method from java.lang.Thread class</p></li>
  <li><p>Another way printing stack trace is using printStackTrace() method of Throwable class</p></li>
  </ol>
  
  <p>Is there any other approach also by which we can get current stack trace  of thread in Java that is more efficient?</p>
  
  <p>Below is the class That I have designed..</p>
  
  <pre><code>public class StackTraceExample 
  { 
  private static final Logger logger = Logger.getLogger(StringReplace.class.getName()); 
  public static void main(String args[]) 
  {
   //calling a method to print stack trace further down 
  first();
  } 
  
  public static void first()
  { 
  second(); 
  }
  
   private static void second() 
   {
   third();
   } 
  
   private static void third()
   {
   //If you want to print stack trace on console than use dumpStack() method 
    System.err.println("Stack trace of current thread using dumpStack() method");
    Thread.currentThread().dumpStack(); 
  
    //This is another way to print stack trace from current method 
  
    System.err.println("Printing stack trace using printStackTrace() method of Throwable "); 
    new Throwable().printStackTrace();
  
    //If you want stack trace as StackTraceElement in program itself than 
    //use getStackTrace() method of Thread class
  
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
  
    //Once you get StackTraceElement you can also print it to console 
    System.err.println("displaying Stack trace from StackTraceElement in Java");
    for(StackTraceElement st : stackTrace)
    {
    // System.err.println(st);
    } 
    }
    }
  </code></pre>
  
  <h2>output :-</h2>
  
  <pre><code>Stack trace of current thread using dumpStack() method 
  java.lang.Exception: Stack trace 
  at java.lang.Thread.dumpStack(Thread.java:1249) 
  at test.StringReplace.third(StringReplace.java:38) 
  at test.StringReplace.second(StringReplace.java:31) 
  at test.StringReplace.first(StringReplace.java:27)
  at test.StringReplace.main(StringReplace.java:23)
  
  
  Printing stack trace using printStackTrace() method of Throwable 
  java.lang.Throwable
  at test.StringReplace.third(StringReplace.java:42)
   at test.StringReplace.second(StringReplace.java:31)
   at test.StringReplace.first(StringReplace.java:27)
   at test.StringReplace.main(StringReplace.java:23) 
   displaying Stack trace from StackTraceElement in Java
  </code></pre>