I was catching an exception and trying to write the stack trace to the logs like this:
log.warn(e.getMessage());
But all it said was
Using log4j this is done with:
logger.error("An error occurred", exception);
The first argument is a message to be displayed, the second is the exception (throwable) whose stacktrace is logged.
Another option is commons-logging, where it's the same:
log.error("Message", exception);
With java.util.logging this can be done via:
logger.log(Level.SEVERE, "Message", exception);
If you using Java 8 you can do the following:
LOGGER.error("Caught exception while methodX. Please investigate: "
+ exception
+ Arrays.asList(exception.getStackTrace())
.stream()
.map(Objects::toString)
.collect(Collectors.joining("\n"))
);
You can use
logger.log(Level.WARN, "logged exception", ex);
or
logger.warn("logged exception", ex);
Resources :
Usually:
log.warn("message", e);
But it depends on your logging framework too.
In your exception method, the underlying String
which contains the message is null
.
The above answer, now struck out, still holds, except that e
is not null, but the detailMessage
private instance variable on the Throwable
class is null, which is why e.getMessage()
is the String null
, but e.toString()
(which calls underlying null detailMessage.toString
) throws a NullPointerException
.
If you are using a Java version previous to 8, you can try this:
LOGGER.error("Error al recuperar proveedores de la base de datos: " +
e + Arrays.asList(e.getStackTrace()).stream().map(new Function(){
@Override
public Object apply(Object t) {
return t.toString();
}
}).collect(Collectors.joining("\n")));