Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not use System.out.println in server side code

I heard that using System.out.println for logging purposes is a very bad practice and this may force the server to fail.

I don't use this approach but I am very interested in knowing why System.out.println could make so trash things when used in backend code.

like image 468
Oleksandr Avatar asked Dec 22 '11 09:12

Oleksandr


People also ask

Why System out Println should not be used?

It is considered to be bad because System. out. println(); eats more cpu and thus output comes slow means hurts the performance.

How do I bypass System out Println?

You can override the toString() method on your class instead, and then this will be used in all places that want to build a string representation of your instance, not simply System. out. println .

Why do we use Log4j instead of System out Println?

Log4j allows logging on class-by-class basis i.e., each class can be covered whereas System. out. println can be controlled at application level. Through Log4j we can turn on or off the logging at runtime by changing the configuration file.


2 Answers

System.out.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 better approach is to use a logging framework. They use a message queue and write only if no other output is going on.

And another benefit is that you can configure separate log files for different purposes. Something your Ops team will love you for.

Read more here:

  • http://logging.apache.org/log4j/1.2/manual.html
  • Logger vs. System.out.println
like image 199
Lars Avatar answered Oct 18 '22 21:10

Lars


Check out Adam Biens article in the Java Magazine edition November/Dezember about stress testing JEE6 applications - it's free online, you only have to subscribe to it.

On page 43 he shows, that a server applications which manages to handle 1700 transactions per second falls down to only 800 when inserting a single System.out.println with fix String in each.

like image 35
Alexander Rühl Avatar answered Oct 18 '22 20:10

Alexander Rühl