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

后端 未结 6 1245
感情败类
感情败类 2021-02-18 18:07

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

         


        
相关标签:
6条回答
  • 2021-02-18 18:44

    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);
    
    0 讨论(0)
  • 2021-02-18 18:55

    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"))
    );
    
    0 讨论(0)
  • 2021-02-18 18:58

    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
    0 讨论(0)
  • 2021-02-18 18:59

    Usually:

    log.warn("message", e);
    

    But it depends on your logging framework too.

    0 讨论(0)
  • 2021-02-18 19:08

    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.

    0 讨论(0)
  • 2021-02-18 19:10

    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 讨论(0)
提交回复
热议问题