Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid printStackTrace(); use a logger call instead

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

  • Avoid printStackTrace(); use a logger call instead.

What does that mean?

like image 358
user1305398 Avatar asked May 07 '12 06:05

user1305398


People also ask

What can I use instead of printStackTrace?

Avoid printStackTrace(); use a logger call instead.

Why we should not use printStackTrace?

e. printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes. The better thing to do is to use a logging framework (logback, slf4j, java.

Why do you use printStackTrace () method?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.

Should stack trace be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.


2 Answers

It means you should use logging framework like logback or log4j and instead of printing exceptions directly:

e.printStackTrace(); 

you should log them using this frameworks' API:

log.error("Ops!", e); 

Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.

like image 192
Tomasz Nurkiewicz Avatar answered Oct 13 '22 02:10

Tomasz Nurkiewicz


If you call printStackTrace() on an exception the trace is written to System.err and it's hard to route it elsewhere (or filter it). Instead of doing this you are advised using a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)).

Doing that allows you to:

  • write the log statement to different locations at once, e.g. the console and a file
  • filter the log statements by severity (error, warning, info, debug etc.) and origin (normally package or class based)
  • have some influence on the log format without having to change the code
  • etc.
like image 43
Thomas Avatar answered Oct 13 '22 02:10

Thomas