質問

When i run my PMD plugin they say System.out.println has been used. why is System.out.println bad to use and is it a defect when using PMD plugin? and what is the alternative way of over coming this?

役に立ちましたか?

解決 3

System.out.println..

are usually intended for debugging purposes and can remain in the codebase even in production code. By using a logger one can enable/disable this behaviour at will (and by priority) and avoid clogging the Standard out log.

(from SourceMeter Java user guide under "Java Logging Rules")

Import needed (.jar)

Logger site

Example:

import org.apache.log4j.Logger;

class Foo{
    private static final Logger LOG = Logger.getLogger(Foo.class);
    public void testA () {
        System.out.println("Entering test");
        // Better use this
        LOG.info("Entering test");
    }
} 

他のヒント

A logger can be turned ON/OFF using a configuration but System.out.println cannot be. Importantly loggers provide different levels of logging and again can be controlled through a configuration file.

Also using loggers you can configure rotation, purging etc but cannot do the same for sysout. This is useful especially in a production environment, executing a lot of code, and generating a lot of logging.

System.out.println() is considered bad practice for Logging.
Because of

  • No ability to turn it (ON/OFF)
  • No ability to set output levels (TRACE, DEBUG, INFO, WARN, ERROR),
    without having to recompile your code

Another disadvantage is that the standard output of a program can be redirected, for instance and it's not always clear where the output is actually going, for instance if you do this:

java SomeClass > someFile

In this case the use of a logging API will help you.

But there are situations where you genuinely want to print something to the standard output too, for those occasions there is java.io.Console, which cannot be redirected, so if you're running a command line java program, it gives you confidence that the users are seeing the messages intended to them.

Printing excessive amounts of into to System.out can become a performance bottleneck because it is synchronized, code from PrintStream:

public void println(float x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

This is because, PMD defines a java logging rule named SystemPrintln which detects System.out.println in the code and consider as a defect.

Since: PMD 2.1

System.(out|err).print is used, consider using a logger.

This rule is defined by the following XPath expression:

//Name[
    starts-with(@Image, 'System.out.print')
    or
    starts-with(@Image, 'System.err.print')
    ]

And you should be able to modify above XPath expression to override the behavior( I am not sure though) Below link should give you more insight,

http://pmd.sourceforge.net/pmd-4.2.6/rules/logging-java.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top