0

In below code exceptions are logged using

logger.error("error", exceptionType.getMessage);

&

logger.error("error", exceptionType);

Using logger.error("error", exceptionType); logs the exception message and stacktrace. I think using using logger.error("error", exceptionType); is preferred option as it logs stacktrace. But I have encountered both ways methods. Is there a reason to use logger.error("error", exceptionType.getMessage); instead of logger.error("error", exceptionType);

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExceptionTest {

    public static void main(String args[]) {

        try {
            throwsException();
        } catch (Exception e) {
            System.out.println("1");
            logger.error("error", e.getMessage());
        }

        try {
            throwsException();
        } catch (Exception e) {
            System.out.println("2");
            logger.error("error", e);
        }
    }

    private static void throwsException() throws Exception {
        throw new Exception();
    }

    private static Logger logger = LoggerFactory.getLogger(ExceptionTest.class);

}

Output :

1
12.11.2014 10:06:30 ERROR [xceptionTest.main():14] error
2
12.11.2014 10:06:30 ERROR [ExceptionTest.main():21] error
java.lang.Exception
    at ExceptionTest.throwsException(ExceptionTest.java:26)
    at ExceptionTest.main(ExceptionTest.java:18)
Fildor
  • 14,510
  • 4
  • 35
  • 67
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • It depends on you. In what are you interested in logs? Do you want to log stacktrace or just a messages? – Braj Nov 12 '14 at 10:13
  • See also http://stackoverflow.com/questions/7320080/should-you-report-the-message-text-of-exceptions – Raedwald Nov 12 '14 at 10:32

1 Answers1

0

The full stack trace may add unnecessary detail to the log when the error message is detailed enough. For example you don't really need to see the trace for a FileNotFoundException: logging the file name and the error message is enough to know which file could not be opened and why.

Multiline messages like the stack trace can also be problematic in systems where an external process reads the log file. If there's a one to one correspondence between messages and log lines the log parsers become easier to write.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • In a project I participated, we were told to (only when stacktraces may be helpful) add the stacktracing log-entry separately with a higher level (like "trace"). So you can switch tracing on in the development simply by setting the Level from Debug or Info to Trace. – Fildor Nov 12 '14 at 10:42