Logger Object vs Static Logging Methods – Why Use a Logger Object?

development-processlogging

Taking an example of a simple Ruby on Rails application. It creates a Logger object during application load process:

# in environment.rb
config.logger = Logger.new(<STDOUT | file | whatever>)

# and in our application we use this object
logger.warn "This process is taking too long to process. Optimization needed."

My question is, why don't we use class methods (or static methods) for logging? Won't Logger.warn scale than Logger.new.warn? Or atleast Logger.warn seems intuitive than Logger.new.warn.

Even if Logger.new is a singleton object, what advantages does it offer?

Best Answer

Here's an example that uses Java. It's been a while since I've used log4j, but from what I remember, the whole log4j logging tool would initialize from an XML file. The XML file itself could contain multiple loggers with different configurations(where you write to, what levels are written, etc). So, in this case you would have logger objects rather than logger static methods in order to specify which logger you want to invoke. Ie.

Logger logger = Logger.get("Network");

would log things related to network connectivity, dropped packets, etc, or

Logger logger = Logger.get("Application");

which would log things related to your business logic/application. At least with log4j you could also configure which log levels actually get written out(info, trace, warn, error, debug being the default levels available).

If you had static methods, the best you could do is configure a single logger that would point to standard out, a file, etc, but everything you log would go to the same place. With logger objects, it's easier to make it so your logging information is spread out to multiple files.

Related Topic