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
null
So I changed it to
log.warn(e.toString());
And now it says only
java.lang.NullPointerException
How do I write the full stack trace to the log so I can see where this Exception is being generated in the app?
To print a stack trace to log you Should declare logger and method info(e. toString()) or log(Level.INFO, e. toString()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages.
Accessing Stack Traces with the Thread Class You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.
Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.
A full stack trace allows you to see the chain of files from when your custom tag reached your set breakpoint. If you click on any of the pages in the caller chain then FusionDebug will show you that page and will highlight the line at which the next page in the chain was called.
Usually:
log.warn("message", e);
But it depends on your logging framework too.
You can use
logger.log(Level.WARN, "logged exception", ex);
or
logger.warn("logged exception", ex);
Resources :
Category
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"))
);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With