About logging in java

Question:

The Apache Commons Logging library is given on Habré in the article (I don’t know the meaning of this library, I didn’t use it) and a comment:

For System.out.println to display logs, novice programmers should cut off their hands after a week of training.

So the question is, why is print so bad?

PS I myself do not know the basics of the language very well.

Answer:

Logging is more than just outputting lines to the console. The following parameters take place here:

  • Purpose: it can be a console (stdout), a slightly different console (stderr), a file, a remote log collection server
  • Logging level: for different outputs, there may be a different output level: for example, we drop everything into one file, but store only the last ten megabytes, and send only WARN level messages to the other, but store the history for the last six months
  • Per-package settings: if a specific piece of code is "naughty", you can enable logging only for it
  • Rotation of logs: logs most often need to be stored in files that need to be periodically cleaned up, and at the same time, during the work, continue to write logs
  • Execution context: often just a message is not enough (if the transaction failed, what input parameters contributed to this?), So there are things like MDC, so that when processing a specific user, a map {processed user id: 12345} added before each of your messages
  • Parameter substitution: writing Logger.debug("Transaction #{} has failed with message '{}'", transaction.getId(), e.getMessage()) much more convenient than writing System.out.ptintln("Transaction #" + transaction.getId() + " has failed with message '" + e.getMessage() + "'") . In addition to convenience, this allows you not to concatenate strings if the logging level is higher than the message itself (that is, at the INFO level, messages with the DEBUG level will not waste resources on concatenation) and group log messages by pattern (search in the logs instead of just the word "transaction "specific pattern).

The logging library deals with all this, and it greatly simplifies life when you need to switch from one model to another, for example, when it becomes impractical to store logs near the application, to switch to a remote server, you just need to connect a new appender and restart the application. In addition, there is a situation when there are so many logs that I / O does not have time to cope – as a rule, they do not think about problems of this kind until they appear, and in the libraries (I hope) some prudent steps have already been taken (for example, logback absolutely by default tries to add the message five times in case something went wrong).

Scroll to Top