Avoid printStackTrace(); use a logger call instead

前端 未结 7 1233
我寻月下人不归
我寻月下人不归 2020-12-07 11:05

In my application, I am running my code through PMD.It shows me this message:

  • Avoid printStackTrace(); use a logger call instead.
7条回答
  •  独厮守ぢ
    2020-12-07 11:30

    A production quality program should use one of the many logging alternatives (e.g. log4j, logback, java.util.logging) to report errors and other diagnostics. This has a number of advantages:

    • Log messages go to a configurable location.
    • The end user doesn't see the messages unless you configure the logging so that he/she does.
    • You can use different loggers and logging levels, etc to control how much little or much logging is recorded.
    • You can use different appender formats to control what the logging looks like.
    • You can easily plug the logging output into a larger monitoring / logging framework.
    • All of the above can be done without changing your code; i.e. by editing the deployed application's logging config file.

    By contrast, if you just use printStackTrace, the deployer / end user has little if any control, and logging messages are liable to either be lost or shown to the end user in inappropriate circumstances. (And nothing terrifies a timid user more than a random stack trace.)

提交回复
热议问题