GeeCON Prague 2014*
The moose likes Java in General and the fly likes Storing stacktrace of an exception to the database. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Storing stacktrace of an exception to the database." Watch "Storing stacktrace of an exception to the database." New topic
Author

Storing stacktrace of an exception to the database.

Alok Pota
Ranch Hand

Joined: Mar 07, 2001
Posts: 185
When an exception is thrown, you can print the stacktrace to the default PrintWriter (System.out) or a specified PrintWriter. However if I wanted to log the exception
stacktrace to the database how do I get the stacktrace?
I know there is a toString() function of the exception but that does not give the stack trace.
Alok Pota
Ranch Hand

Joined: Mar 07, 2001
Posts: 185
public class ExceptionWriter extends PrintWriter {
public ExceptionWriter() {
super(new StringWriter());
}
public ExceptionWriter(OutputStream out) {
super(out);
}
public ExceptionWriter(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
}
public ExceptionWriter(Writer out) {
super(out);
}
public ExceptionWriter(Writer out, boolean autoFlush) {
super(out, autoFlush);
}

public StringBuffer getBuffer() {
if (super.out instanceof StringWriter) {
return ((StringWriter)out).getBuffer();
}
throw new IllegalArgumentException("Underlying writer is not a StringWriter");
}
}

to use the above
Throwable t;
ExceptionWriter ew = new ExceptionWriter();
t.printStackTrace(ew);
String stackTrace = ew.getBuffer().toString();
 
GeeCON Prague 2014
 
subject: Storing stacktrace of an exception to the database.