Reputation: 217
I need to put the stack trace from exeception in a log, so I do:
final static Logger logger = LoggerFactory.getLogger(MyClass.class);
try{
..
}catch(NumberFormatException number_format){
logger.error(number_format.exception.getStackTrace().toString());
}
But it doesn't work because it print me Ljava.lang.StackTraceElement;@775a19fe
.Anyone can help me?
Upvotes: 1
Views: 2706
Reputation: 364
The Apache Commons Lang library can provide a readable stack trace from a given exception, specifically ExceptionUtils.
try {
..
}
catch(NumberFormatException e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
Upvotes: 0
Reputation: 2531
getStackTrace()
returns StackTraceElement[]
for which the toString()
function is not overridden so you get what you have in the java.lang.Object
class:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
That's why you get this message. You should use the getMessage()
function of the Exception
class instead.
If you want the stacktrace message, you can get it like so:
Arrays.stream(e.getStackTrace()).map(String::valueOf).collect(Collectors.joining("\n"))
and then output it.
Upvotes: 1
Reputation: 2691
It depends a bit on your logging library, but usually you do the following:
logger.error("Something went wrong", exception);
Upvotes: 0
Reputation: 131326
To log a stracktrace with a logger, use the overloaded method of the logger that suits to :
Logger.error(String msg, Throwable t);
Slf4j, Log4j, LogBack, common-logging... all of these distinguish Logger.error(String msg)
to log an error message and Logger.error(String msg, Throwable t)
to log both an error message and the stracktrace of a Throwable
.
So write something like :
final static Logger logger = LoggerFactory.getLogger(MyClass.class);
try{
..
}
catch(NumberFormatException e){
logger.error("issue in ...", e);
}
Upvotes: 2