File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Tracking Stack Trace Information Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Tracking Stack Trace Information" Watch "Tracking Stack Trace Information" New topic

Tracking Stack Trace Information

James Gordon
Ranch Hand

Joined: Aug 09, 2002
Posts: 106
The Exception class getMessage method return a string which we can store and manipulate but the details are pretty little.
With printStackTrace, we see a lot more but I can't seem to find any way to store the information printed.
Reason for this is that I would want to pass the stack trace detail to a Logger object for logging,
instead of printing 'directly' to a file.
Any ideas?
Thanks in advance.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Well, if you're using Java 1.4, this is easy. Exceptions (all Throwables in fact) now have a getStackTrace() method which makes it easy to access all the info in the stack trace. Moreover if you use the java.util.logging.Logger class, you have can use many methods which accept a Throwable as a parameter, which means the Logger knows how to log the stack trace for you without any extra effort on your part (other than passing the parameter.)
If you're not using 1.4, whatever logging mechanism you're using (Log4J maybe?) should have methods for logging exceptions. If you're writing the logger yourself, write methods to handle exception info. The best (only?) way to extract a stack trace prior to 1.4 is by printing the stack trace to something that saves the info. The simplest is to use a StringWriter wrapped in a PrintWriter. The latter is necessary because a there's no printStackTrace(Writer), just printStackTrace(PrintWriter). Here's a method to store a stack trace as a String:

"I'm not back." - Bill Harding, Twister
James Gordon
Ranch Hand

Joined: Aug 09, 2002
Posts: 106
Hi Jim,
Thanks for the sample code. I'm using jdk 1.3,
so I guess that is the only way !
I agree. Here's the link:
subject: Tracking Stack Trace Information
It's not a secret anymore!