What's wrong with using System.err in Java?

user128807 picture user128807 · Jun 26, 2009 · Viewed 11.6k times · Source

I'm using the Enerjy (http://www.enerjy.com/) static code analyzer tool on my Java code. It tells me that the following line:

System.err.println("Ignored that database");

is bad because it uses System.err. The exact error is: "JAVA0267 Use of System.err"

What is wrong with using System.err?

Answer

akarnokd picture akarnokd · Jun 26, 2009

Short answer: It is considered a bad practice to use it for logging purposes.

It is an observation that in the old times when there where no widely available/accepted logging frameworks, everyone used System.err to print error messages and stack traces to the console. This approach might be appropriate during the development and local testing phase but is not appropriate for a production environment, because you might lose important error messages. Because of this, in almost all static analysis tools today this kind of code is detected and flagged as bad practice (or a similarly named problem).

Logging frameworks in turn provide the structured and logical way to log your events and error messages as they can store the message in various persistent locations (log file, log db, etc.).

The most obvious (and free of external dependencies) hack resolution is to use the built in Java Logging framework through the java.util.logging.Logger class as it forwards the logging events to the console by default. For example:

final Logger log = Logger.getLogger(getClass().getName());
...
log.log(Level.ERROR, "Something went wrong", theException);

(or you could just turn off that analysis option)