how to print an exception using logger?

前端 未结 4 2080
无人共我
无人共我 2021-02-18 15:15

I have a situation in which I want to print all the exception caught in catch block using logger.

 try {
        File file = new File(\"C:\\\\className\").mkdir(         


        
相关标签:
4条回答
  • 2021-02-18 15:27

    You can use this method to log the exception stack to String

     public String stackTraceToString(Throwable e) {
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement element : e.getStackTrace()) {
            sb.append(element.toString());
            sb.append("\n");
        }
        return sb.toString();
    }
    
    0 讨论(0)
  • 2021-02-18 15:41

    You should probably clarify which logger are you using.

    org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

    So, probably you need to write:

    logger.error("BOOM!", e);
    

    If you need to log it with INFO level (though, it might be a strange use case), then:

    logger.info("Just a stack trace, nothing to worry about", e);
    

    Hope it helps.

    0 讨论(0)
  • 2021-02-18 15:41

    Try to log the stack trace like below:

    logger.error("Exception :: " , e);
    
    0 讨论(0)
  • 2021-02-18 15:43

    Use: LOGGER.log(Level.INFO, "Got an exception.", e);
    or LOGGER.info("Got an exception. " + e.getMessage());

    0 讨论(0)
提交回复
热议问题