Need a logging package that will log the stacktrace

D

Dean Schulze

Is there a Logger that will easily log my stacktrace (what I get with
ex.printStackTrace())? I've searched the log4j docs and found nothing
about logging the stacktrace.

I can do this myself with

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.error(stacktrace);

but I don't want to duplicate this code all over the place.

If log4j won't do this for me is there another logging package that will
log the stacktrace for me?

Thanks.
 
J

Joe Attardi

Hey Dean,

Worst case, you could just have a helper class with a static method to
log the stack trace. It could be something like

public class ExceptionLogger {
public static void logException(Logger logger, Throwable ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.error(stacktrace);
}
}

then in your code wherever you need to log it, just call
ExceptionLogger.logException(logger, ex);

What do you think of that approach?

-- Joe Attardi
 
D

Dean Schulze

That will cut down on code duplication.

I'm surprised that the standard and defacto standard logging APIs don't
include the stacktrace. I thought there'd be one out there that did this.
 
D

Daniel Dyer

That will cut down on code duplication.

I'm surprised that the standard and defacto standard logging APIs don't
include the stacktrace. I thought there'd be one out there that did
this.

If you look at the Log4J API docs you will see that each of the trace,
debug, info, warn, error and fatal methods are overloaded with a version
that takes two parameters, the second parameter being a Throwable. These
overloaded methods will output the stack trace from that Throwable along
with the message that you pass in the first parameter.

Dan.
 
P

Patrick May

Daniel Dyer said:
If you look at the Log4J API docs you will see that each of the
trace, debug, info, warn, error and fatal methods are overloaded
with a version that takes two parameters, the second parameter being
a Throwable. These overloaded methods will output the stack trace
from that Throwable along with the message that you pass in the
first parameter.

The java.util.logging.Logger class has this capability as well if
you use the log(Level,String,Throwable) method instead of the
convenience methods.

Regards,

Patrick
 
D

Dean Schulze

That worked. Thanks.

I knew I had seen stack traces in .log files, but their API isn't very
intuitive.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top