I'm using the PMD plugin for eclipse and it gives me an error when using System.out.println()
with the explanation:
System.(out|err).print is used, consider using a logger.
My question is - What is a Logger? How is it used to print to the screen? Why is it better?
Answer 513dd6ba05d6f4318a006aee print will just print the text to console. console. log() actually records it and we can use it for many purposes like email it for bug report.
The default logging level is warning. Print- The only time when print() is a better option than logging is when the goal is to display a help statement for a command line application. The log record which is created with every logging event, contains readily available dingostic information.
println is an IO-operation and therefor is time consuming. The Problem with using it in your code is, that your program will wait until the println has finished. This may not be a problem with small sites but as soon as you get load or many iterations, you'll feel the pain.
The call to LogFactory. getLog() is from the commons-logging api. log4j is a logging framework, i.e. it provides the code to log messages. Commons-logging is an abstraction layer for logging frameworks, it doesn't log anything itself.
See this short introduction to log4j.
The issue is in using System.out
to print debugging or diagnostic information. It is a bad practice because you cannot easily change log levels, turn it off, customize it, etc.
However if you are legitimately using System.out
to print information to the user, then you can ignore this warning.
If you are using System.out|err.println(..) to print out user-information on console in your application's main()-method, you do nothing wrong. You can get rid of the message via inserting a comment "//NOPMD".
System.out.println("Fair use of System.out.println(..).");// NOPMD
There is a "Mark as reviewed"-Option in the PMD-Violations Outline for this purpose.
Of course you can trick PMD with following code snippet:
PrintStream out=System.out; out.println("I am fooling PMD.");
Outside of your main()-Method use a Log-System like eg Log4j.
UPDATE:
You can also modify the PMD-Rule "SystemPrintln" to use the following XPath:
//MethodDeclaration[@MethodName!="main"]//Name[ starts-with(@Image, 'System.out.print') or starts-with(@Image, 'System.err.print') ] | //Initializer//Name[ starts-with(@Image, 'System.out.print') or starts-with(@Image, 'System.err.print') ]
This will ignore System.out.println etc in any method named 'main' in your code, but check for System.out.println in initializer code. I like this, because from my point of view, System.out.println is safe in method 'main(String args[])'. But use with caution, I have to check, where in the AST a System.out.println can occur also and have to adapt the XPath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With