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

为君一笑 提交于 2019-12-05 12:51:23

问题


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?


回答1:


Usually:

log.warn("message", e);

But it depends on your logging framework too.




回答2:


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



回答3:


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



回答4:


If you using java8 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"))
        );



回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/3717249/how-do-you-write-a-full-stack-trace-to-the-log

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!