I have a jsp web application where I print the error stacktrace as follows:
catch (SQLException e) {
e.printStackTrace(System.out);
}
but in production environment I do not want my application to print something. I want to put a global flag (Debug = true for example) . then I will update the codes like this
if(debug) e.printStackTrace(System.out);
I have many pages in my application. Now where should i declare the debug variable ? I can put it in web.xml file but I am not sure if its safe or not.Thanks
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.