struts - logging for each layer (Action, DAO)
I am new to struts and I would like to understand how do I handle logging for each layer(JSP/ActionForm, Action, DAO) of the application.
I notice as time goes by the error log file maybe too cluttered and unfriendly to view. How can I improve on the logging patterns to separate the errors thrown by each layer of the application?
and I couldnt find a way to handle excepti开发者_StackOverflow中文版ons encounter on jsp page as well.
Code Template for Action
public ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
try {
// calls the DAO
}
catch (CustomDAOException e) {
log.error(e);
// inform application there is an error
}
catch (Exception e) {
log.error(e)
// inform application there is an error
}
}
Code Template for DAO
public void update() throw CustomDAOException {
try {
// Prepare a statement to insert a record
String sql = "INSERT INTO my_table (col_string) VALUES(?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
// Insert 10 rows
for (int i=0; i<10; i++) {
// Set the value
pstmt.setString(1, "row "+i);
// Insert the row
pstmt.executeUpdate();
}
} catch (SQLException e) {
throw new CustomDAOException(e);
}
Set up an exception-handler in your struts-config, let all exceptions bubble up to that, and log them there. That will make all your exception-catching-and-logging code unnecessary.
As for the JSP, don't do anything error-prone in the JSP, do it in the action, then add the results to the request attributes.
I'm guessing you might be using an ancient version of Struts 1, I've seen similar code where they had to catch exceptions in the actions, apparently because exception-handlers didn't work with early versions of struts. That's fixed now, the first thing you should do is upgrade the application to at least 1.2, preferably 1.3. Using an obsolete version of a web framework is a bad thing, there are security patches among the fixes you're missing out on, so your application may be insecure.
Looking at your sample code, it really doesn't seem that bad. I don't see the point of catching different types of exception in your actions (which might be clearer if I knew what you elided), but I don't see bad practices like logging things in each layer and then rethrowing them (so that the same stack trace shows up repeatedly), or logging exceptions and returning null (so the calling code may not know anything went wrong), or just eating exceptions without a trace. If you give more specifics on what problems you want to solve maybe I or somebody else can be more helpful.
精彩评论