Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Tracking Stack Trace Information

 
James Gordon
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
James Gordon
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jim,
Thanks for the sample code. I'm using jdk 1.3,
so I guess that is the only way !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic