Use a logging API like JB Nizet suggests. They are rather simple to use. Here's a small example to implement logging using Log4j from Apache (http://logging.apache.org/log4j) which is very popular.
All your classes would have an instance of logger ready
private static final Logger log = Logger.getLogger(this.getClass());
Then at places where you catch exceptions
catch (SQLException e) {
log.debug(e);
}
Then just configure Log4j using log4j.properties
in your classpath
log4j.appender.stdout.Target=System.out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=debug, stdout
To turn of logging is then as simple as changing
log4j.rootLogger=warn, stdout
What this means is that you're only interested in log statements that are at a level of warning or above (like error, or fatal). There are about six log levels: fatal, error, warn, info, debug and trace. When you set a level all log statements that log at a level below what you've specified are ignored.
Please, note that I've simplified things above. It's recommended to use log4j.xml
instead of .properties
. Latest APIs also allow you to gain some performance with a check done before logging
catch (SQLException e) {
if (log.isDebugEnabled()) log.debug(e);
}
But, the real selling point of using the framework instead of just checking a Globals.DEBUG
flag before doing a printStackTrace()
is that it's future proof. Say tomorrow if you have to log things to a file just switch from ConsoleAppender
to a FileAppender
. Want an email delivered on something fatal
use an SMTPAppender
for just this use case. Other appenders stay configured as they are.