It's 9102, you still don't know the harm of System.out.println!

Recently, an old project needs to be changed. The project code is very large, which can be called "big and complete".

The code in the old project, after several generations of writing, is very difficult to read, and the source is System.out.println(). Today I take a moment to tell you why most people are told not to use Java Use System.out.println in the application!

It's 9102, you still don't know the harm of System.out.println!

1. The first reason is that it cannot achieve log output by level. Specifically, it cannot have debug, info, error and other levels of control like the log framework.

2. Its output is not easy for you to quickly trace the code from the log. Including it cannot output specific class names, method names, specific lines of code, etc.

3. The third reason is that its performance is too poor.

It's 9102, you still don't know the harm of System.out.println!

If you pass the synchronized keyword, you will find that if System.out.println is used extensively in the project, it will eventually cause the entire code call to become a "serial" output.

Sometimes it's not that your JVM is not optimized well, and the second is that the code you write is like a draft again!

Interested netizens can do a stress test on System.out.println and see its performance report.

System.out.println performance is not good. When we analyze in depth, the calling sequence is as follows: println -> print -> write() + newLine(). Therefore, some companies completely disable it on the basis of OpenJDK, or replace it with other implementations.

System.out.println VS logging component

Take Log4J as an example here. Log4J has multiple logging levels. If we are writing a small program just for experiment/learning purposes then using System.out.println is very good. But when we develop production quality software, we should take care that logging components (log4j, etc.) should be used, and System.out.println should be avoided. why?

  • Flexibility: log4j's logger provides multiple logging levels. We can separate the log information accordingly. For example, X message can only be printed on PRODUCTION, Y message should be printed on ERROR etc.

  • Reconfigurability: log4j only needs one parameter change to turn off all logging.

  • Maintainability: Imagine if we have hundreds of System.out.println all scattered through the application, it will be difficult to maintain the program for a period of time.

  • Granularity: In the application, each class can have a different logger and control accordingly.

  • Practicality: Limit the options for redirecting messages in System.out, but if it is a logger (like log4j), you can provide multiple options. We can even create custom output options and redirect them.

So we should not use System.out.println for logging and debugging (logging and debugging).

Guess you like

Origin blog.51cto.com/15127565/2664964