简体   繁体   中英

Difference between logging exception and exception.printstacktrace

Could you please clarify me the difference when I just used a logger with

 LOGGER.error("Exception is -- " , exception);

and

 LOGGER.error("Exception is -- " , exception.printStackTrace());

Which one is better to get more details about exception?

LOGGER.error("Exception is -- " , exception.printStackTrace());

Its invalid statement. Throwable#printStackTrace method's return type is void and it prints this throwable and its backtrace to the standard error stream.

You may find the difference between LOGGER.error("Exception is -- " , exception); and exception.printStackTrace()

Logging the exception with logger api(Ex. LOG4j, Logback etc) is write way to log or more convenient way as you can pre-define all log related setting. Like -

  • Number Appenders to be defined
  • Log print format
  • Different file for different LOG.LEVEL

etc...

The main difference is that the second one doesn't compile. printStackTrace() is a void method.

Normally, when people involve printStackTrace() , they write

e.printStackTrace();

instead of

LOGGER.error(message, e);

but don't combine these two in one line.

Anyway, never use .printStackTrace() in an application which already has logging because your stack trace may not even make it to the logs, and it will appear in the System.err stream, where nothing should be written from an app which has proper logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM