Suzan Cioc
Suzan Cioc

Reputation: 30097

What is good to do with exception when logging?

Suppose I want to reflect exception in the log.

Should I pass stack trace into log.error() or just Exception's toString()? Or do something better?

How to obtain stack trace string to pass to logger?

Upvotes: 2

Views: 330

Answers (3)

Tim Büthe
Tim Büthe

Reputation: 63734

When using something like log4j, there is an extra parameter for the exception so you typically write something like this:

catch(Exception e){
    logger.error("some message", e);
}

Log4j will take care of printing the stacktrace.

One thing to keep in mind (at least for log4j) is this: When you don't want to log a message but only the exception, you must use:

logger.error("", e);

not

logger.error(e); // bad usage! This uses e.toString()!!

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340693

All modern logging frameworks treat passed Exception object special:

log.error("Danger! High Voltage!", ex);

The framework (let it be or ) will format the stack trace nicely for you. Always log the full stack trace unless you really know what you are doing. Otherwise you can always filter out exceptions from given logger.

Also note that many important exception do not provide meaningful message, NullPointerException being important example.

Upvotes: 5

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

I would go for logging the whole stack trace of course. It's much easier to find it source this way.

I don't know what library you are using for logging but if it does not support to log exceptions, you can get the stacktrace as a string this way:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
exception.printStackTrace(ps);
ps.close();
String stacktrace = baos.toString();

Upvotes: 1

Related Questions