Reputation: 4713
I am developing a demo app using Servlet/JSP and using logging JAR by apache called log4j from http://logging.apache.org/log4j/1.2/
My question is related to where to use logging. Any best practices.?
1 - Should log error messages in try/catch and also throw exception. See example below?
2 - Should use it where we need to use System.out.println("message") for debugging or printing info?
3 - Should use it in production or only in development?
How do you use it in your application?
Am I doing it right or generating useless messages?
try{
con = ConnectionManager.getConnection();
ps = prepareStatement(con, SQL_DELETE, false, values);
int affectedRows = ps.executeUpdate();
if(affectedRows == 0){
log.error("delete: Deleting user failed, no rows affected");
throw new DAOException("Deleting user failed, no rows affected.");
}else{
user.setId(null);
}
}catch(SQLException e){
log.error("delete: " + e.getMessage());
throw new DAOException(e);
}finally{
close(con, ps);
}
try{
Class.forName(DRIVER);
try{
Class.forName(DRIVER);
log.info("Connecting database...");
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
log.info("Database connected!");
}catch(SQLException ex){
throw new RuntimeException("Cannot connect the database!", ex);
}
}catch(ClassNotFoundException e){
log.error("Closing ResultSet failed: " + e.getMessage());
System.exit(-1);
}
Upvotes: 1
Views: 281
Reputation: 301
Loggers are basically used to capture debug statements, info or error messages in log files.
Ideally you should not use System.out.println("message") anywhere in your web app, only use loggers, like log4j.
All error messages caught in try-catch block should be logged as
if(log.isErrorEnabled()) { log.error("error message"); }
Statements which you use to debug your app or to print some development information in logs can be written as:
if(log.isDebugEnabled()) { log.debug("debug message"); }
or
if(log.isInfoEnabled()) {
log.info("debug message");
}
Once you have added loggers in above format in your code, You can enable-disable them from being printed in logs by setting logging level in Log4j configuration (properties or XML file), without recompiling source code.
For Example,
if logging leve is DEBUG -> debug, info and error messages will be logged in log file.
if logging leve is INFO -> only info and error messages will be logged in log file (no debug messages).
if logging leve is ERROR -> only error messages will be logged in log file (no deebug or info messages).
Ideally, in production we set logger level to ERROR and in development logger level is set to DEBUG or INFO.
Log4j is much more powerful and useful than what i have written above. For more details refer to Log4j manual.
Upvotes: 1