Java Logging Made Easy

Not long ago I joined a friend of mine for lunch to discuss what we were both doing in our new jobs. My friend had recently started a job with a local IT training company teaching several topics including a few Java courses.

"So what kind of logging are you using?" I asked. After all, you need some kind of output to do quick and easy debugging. The debugger is nice but is sometimes more cumbersome than it is worth.

"We are just printing to standard out."

I quickly inquired why they couldn't use a standard logging utility like Log4J or the built in java.util.logging. I have always been a stickler for teaching students how to do things right the first time. So why teach them to log using System.out when that is the last thing you do in a real world application? To my friend it was a matter of time. They just didn't have the time to teach the students how to do proper logging and cover all the other topics in the class.

But I had a solution - a simple approach to logging that would be easy for novices to learn and would be easy to convert to more sophisticated logging in the future.

What I suggested was to use a logging wrapper. Have the students start out by creating a XYZAppLogger class that all their code calls when they need to log. Then have the XYZAppLogger dump everything to System.out or System.err.

What are the advantages of doing this?
  • The XYZAppLogger, as you will see below, is a very simple class so it helps new students get started by teaching them to type in, compile and run a program. This is a trivial task for experienced Java programmers and a nice intro for beginners.
  • By having all their code call XYZAppLogger, when a student is ready to start using a sophisticated logging utility, they only change one file - the XYZAppLogger.
  • If a student decides they don't like the logging utility they choose, they can easily switch to something else. I had a programmer tell me once that they thought it was a waste of time to use a logging wrapper. "Just call the logging utility directly. You will never change your logging." Two months later I sat at my computer converting all my code from java.util.logging to Log4J. I knew better - so why did I listen to that other programmer? I use a logging wrapper for all my logging now, just in case. (Note, since about 2008 we have started using SLF4J which is a common logger wrapper and have it delegate to Log4J.)
  • Turning logging off throughout the whole application is easy - you just comment out the System.out.println and System.err.println statements in the XYZAppLogger
  • With a simple if/else in the XYZAppLogger you can turn logging on or off fo