开发者

How do you write a full stack trace to the log?

I was catching an exception and trying to write the stack trace to the logs like this:

log.开发者_StackOverflow中文版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?


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 :

  • How to print the stack trace of an exception using Log4J (or Commons Logging)
  • logging.apache.org - Category


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"))
);


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);


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")));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜