Skip to content

Instantly share code, notes, and snippets.

@mikaelhg
Created November 29, 2011 18:57
Show Gist options
  • Save mikaelhg/1405955 to your computer and use it in GitHub Desktop.
Save mikaelhg/1405955 to your computer and use it in GitHub Desktop.
Customizable Expression Trace Interceptor
package gumi.spring;
import java.util.HashMap;
import java.util.Map;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.springframework.aop.interceptor.AbstractTraceInterceptor;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.StopWatch;
/**
* Like Spring's CustomzableTraceInterceptor, but using SpEL templates.
*/
public class CustomizableExpressionTraceInterceptor extends AbstractTraceInterceptor {
private final ExpressionParser parser = new SpelExpressionParser();
private Expression enter, exit, exception;
@Override
protected Object invokeUnderTrace(final MethodInvocation invocation, final Log log) throws Throwable {
final String name = invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName();
final StopWatch stopWatch = new StopWatch(name);
Object returnValue = null;
boolean exitThroughException = false;
try {
stopWatch.start(name);
log.debug(enter.getValue(evaluationContext1(invocation)));
returnValue = invocation.proceed();
return returnValue;
} catch (final Throwable ex) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
exitThroughException = true;
log.debug(exception.getValue(evaluationContext3(invocation, stopWatch, ex)), ex);
throw ex;
} finally {
if (!exitThroughException) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
log.debug(exit.getValue(evaluationContext2(invocation, stopWatch, returnValue)));
}
}
}
private static Object evaluationContext1(final MethodInvocation mi) {
final Map<String, Object> ret = new HashMap<>();
ret.put("i", mi);
return ret;
}
private static Object evaluationContext2(final MethodInvocation mi, final StopWatch sw, final Object returnValue) {
final Map<String, Object> ret = new HashMap<>();
ret.put("i", mi);
ret.put("s", sw);
ret.put("r", returnValue);
return ret;
}
private static Object evaluationContext3(final MethodInvocation mi, final StopWatch sw, final Throwable t) {
final Map<String, Object> ret = new HashMap<>();
ret.put("i", mi);
ret.put("s", sw);
ret.put("e", t);
return ret;
}
public void setEnterMessage(String enterMessage) {
this.enter = parser.parseExpression(enterMessage);
}
public void setExitMessage(String exitMessage) {
this.exit = parser.parseExpression(exitMessage);
}
public void setExceptionMessage(String exceptionMessage) {
this.exception = parser.parseExpression(exceptionMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment