views:

310

answers:

4

First, I am throwing run time exceptions for all unrecoverable exceptions, this causes these exceptions to travel up to the conainter, where I currently use an error page (defined in web.xml). In this error page is a scriptlet that invokes the logger.

The issue I am having with this is that the exception is no longer on the stack at this invocation. I have access to it from a request scope variable ("javax.servlet.error.message"). This string is the stack trace. I need this stack trace for logging purposes obviously, and on different app servers "javax.error_message" can be turned off for security reasons.......

So my question is, how can best log runtime exceptions from within j2ee apps without wrapping everything in this:

try {} catch (Exception e) {logger.log(...)}

?

I want some way to invoke the logger from the container maybe... right before the container catches the exception for example.

+1  A: 

There is nothing I know of in Servlet API to accomplish this.

However, you can do this in Tomcat with an instance listener. You can install a listener in context.xml like this,

<InstanceListener>myapp.MyListener</InstanceListener>

Tomcat fires InstanceEvent.AFTER_SERVICE_EVENT event right after the container catches the exception and before it throws the exception again. You can invoke the logger right there.

ZZ Coder
Do you know if this can be done in Oracle Weblogic or Oracle Application Server?
Zombies
No experience with other containers. It's very likely they all have something similar (probably undocumented) because the container needs the hook for its own lifecycle management.
ZZ Coder
It seems that Oracle does allow for this through JSF, which is where we will do this on our ADF Faces (a JSF implementation from Oracle): http://database.in2p3.fr/doc/oracle/Oracle_Application_Server_10_Release_3/web.1013/b28967/web_val008.htm
Zombies
A: 

Correct me if I'm wrong, but the 'exception' object is present as a variable.. called 'exception' in your 'error' jsp. You could always use this object to log retrieve the exception information and log in in the error jsp itself.

Ryan Fernandes
A: 

AOP (Aspect Oriented Programming) would be my first choice.

You define:

  • join point (a runtime exception is thrown).
  • advice (your code to log the exception).
  • point cuts (which parts of your applications are "listening" this aspect).

Take a look at http://www.aspectj.org/

SourceRebels
+1  A: 

I found a solution. By adding a response filter and wrapping chain.doFilter(req, resp) like so:

try {
    chain.doFilter(req,resp);
{ catch (Exception e) {
    logger.error("", e);
    throw new RuntimeException(e);
}

This works fine so far and isn't dependent on a particular framework or app server.

Zombies