Reputation: 19854
I've read many different articles/threads on this, but have yet to determine the best way to perform Apache Commons logging in my JSP.
To provide some context, I am adding improved error logic to an application that was originally developed using Spring 2. So now we have Controllers that were created using Spring 2 and Spring 3.
So rather than using Spring MVC 3's Exception Handling at Controller level, I think it would be best to have a JSP configured in the web.xml that would log all propogated exceptions for all Controllers.
Surprisingly, I don't see an easy way to perform logging within a JSP using tag libraries. Apache Commons seems to have a retired tag library for logging, but this is based on log4j as opposed to Apache Commons Logging itself.
So, instead I'm performing the following programmatically within my JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page isErrorPage="true" %>
<% Log logger = LogFactory.getLog(this.getClass()); %>
<html>
<head>
</head>
<body>
<%
StringBuilder stringBuilder = new StringBuilder("\n" + exception);
for(StackTraceElement element : exception.getStackTrace())
{
stringBuilder.append("\n" + element.toString());
}
logger.error("Unhandled exception caught: " + stringBuilder.toString());
%>
<p>Text here</p>
</body>
</html>
So my question is this....is there a better way to perform this logging? The above works, but seems unnecessarily awkward for what should be a common task
Upvotes: 0
Views: 1280
Reputation: 1108802
Putting raw Java code in a JSP file is indeed awkward. As to your concrete functional requirement,
log all propogated exceptions for all Controllers
the common practice is to use a Filter
for that which is mapped on /*
.
E.g.
@WebFilter("/*")
public class ExceptionFilter implements Filter {
private Log logger = LogFactory.getLog(getClass());
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (ServletException e) {
logger.error("Unhandled exception caught", e);
throw e;
}
}
// ...
}
Note that you don't need to build the stack trace yourself. The logger already does that if you pass the exception as 2nd argument. Still then, you could have used among others Throwable#printStackTrace(PrintWriter)
for that.
Upvotes: 1