how to print an exception using logger?

十年热恋 提交于 2020-01-01 07:33:28

问题


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();
        fh = new FileHandler("C:\\className\\className.log");
        logger.addHandler(fh);
        logger.setUseParentHandlers(false);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    } catch (Exception e) {
        logger.info(e);
    }

i got the error logger cannot be applied to java.io.Exception...

My concern is if I do so many thing in try block and I keep only one catch block as catch(Exception e), Then is there any way using logger that print any kind of exception caught in catch block ? Note: we are using java.util.logging.Logger API


回答1:


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.




回答2:


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




回答3:


Try to log the stack trace like below:

logger.error("Exception :: " , e);



回答4:


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


来源:https://stackoverflow.com/questions/15805460/how-to-print-an-exception-using-logger

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