Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 554
user128807 Avatar asked Jun 26 '09 15:06

user128807


1 Answers

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)

like image 151
akarnokd Avatar answered Nov 12 '22 03:11

akarnokd