2

Why is it a good practice to use logger.debug() instead of System.out.println()?

I understand that log4j allows you to control what you wish to print (DEBUG,FATAL,INFO, etc), but apart from that, is there any other benefit?

James Dunn
  • 8,064
  • 13
  • 53
  • 87
Victor
  • 16,609
  • 71
  • 229
  • 409

3 Answers3

5

A Logger adds so much more value to your logging.

  • Log levels: In a production environment you don't care about some levels (ex: debug info), only serious errors and system crashes.
  • Log filtering: Filter what components are allowed to log.
  • Log formatting: Control the information and its format contained in the log. You can setup defaults (like time and thread id) or add more specific ones per statement.
  • The log destination: You can set up your logger to write to a file, to emails, to databases, etc.
  • A policy for keeping and archiving logs: Let the logger manage the logs, keep some history, delete older

Also, Loggers are usually synchronized, so your print statements aren't written over eachother. You cannot guarantee that with System.out.

You can implement all this with System.out, but it would be so complex and tedious.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

If your code is ever used in a web service or a system service, using debug statements will ensure that they appear in the services logs. If not you risk them being printed to a hidden console window and being lost.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

Specialized loggers offer a number of benefits over plain standard output:

  • logical separation of logging, in at least two orthogonal areas: subsystem and importance
  • flexibility - there are many predefined ways to output and store log data, and you can roll you own, if you really want
  • configurability - you can precisely control what and where to log, and all of this is external to the code that actually uses logging, making it simple and inobtrusive
  • formatting - you don't need to manually append all the bookkeeping information, such as the class name, time etc. Logger does that for you, in an entirely configurable way, allowing you to write simple, clear logging code and retain all the benefits, like filtering and precise information.
  • speed - loggers are optimized not to introduce much overhead
Marcin Łoś
  • 3,226
  • 1
  • 19
  • 21