Java – how to print exceptions using logger?
I have a situation where I want to use the logger to print all exceptions caught in the catch block
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 get that the error logger cannot be applied to Java io. Exception …
I am concerned that if I do so many things in the try block and I only keep one catch block as catch (exception E), is there any way to use logger to print and capture any type of exception in the catch block? Note: we use Java util. logging. Logger API
Please guide me... Thank you, sir
Solution
You should know which recorder you are using
org. apache. commons. logging. The log interface has methods void error (object message, throwable T) (and void info (object message, throwable T)), which records stack traces together with custom messages The log4j implementation also has this method
So maybe you need to write:
logger.error("BOOM!",e);
If you need to log in at the info level (but this can be a strange use case), then:
logger.info("Just a stack trace,nothing to worry about",e);
I hope it helps