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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Pankaj
  • 2,057
  • 3
  • 15
  • 10

4 Answers4

45

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.

Giorgi Kandelaki
  • 788
  • 1
  • 7
  • 10
5

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

user2771704
  • 5,994
  • 6
  • 37
  • 38
Elobilo
  • 61
  • 1
  • 1
  • 2
    If exception is unexpected then I recommend to use SEVERE of WARNING log level for log message – Alex Sep 25 '14 at 12:03
  • 1
    Yes, for unexpected exceptions that would probably be true. I was answering the question though, where the questioner was using info log level to log and hence my example using info. – Elobilo Oct 23 '14 at 08:11
4

Try to log the stack trace like below:

logger.error("Exception :: " , e);
John Jai
  • 3,463
  • 6
  • 25
  • 32
  • i tried this, got the error Symbol not found symbol : method error(java.lang.String,java.io.IOException) location: class java.util.logging.Logger logger.error("Exception:: ",e); – Pankaj Apr 04 '13 at 08:28
  • 1
    @Pankaj Aren't you using Log4j for logging. The method is present in `org.apache.log4j.Logger` – John Jai Apr 04 '13 at 12:29
1

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();
}
Shashi
  • 12,487
  • 17
  • 65
  • 111