Video in progress

Why do we use a logger instead of System.out.println in production code?

A logger adds the level, time, thread name and class automatically, lets you switch off unneeded logs through configuration, and lets you route output to a file, JSON or an external system. println has none of these.

📖 Answer

System.out.println("user topilmadi") is almost useless in prod: when it was written, which thread, which class are all unknown. To turn it off you have to change the code and redeploy.

With a logger:

private static final Logger log = LoggerFactory.getLogger(UserService.class);

log.debug("User qidirilmoqda: id={}", id);

What you gain:

  • levels: DEBUG is off in prod, and when there's a problem you turn it on for a single package;
  • format: time, level, thread, logger name, and later a traceId, added automatically;
  • routing: console, file, JSON, Loki/Elasticsearch, with no code change, only configuration;
  • exception stack traces come out properly formatted.

One more thing: System.out is synchronous and has a lock inside. Under a multi-threaded load it can slow things down noticeably.