在项目中,我们往往需要记录数据库操作的时间,根据操作时间的不同,分别记录不同等级的日志。
首先我们可以写一个类实现MethodInterceptor接口:
import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 自定义 AOP 处理时间类 */ public class TimeHandler implements MethodInterceptor { /** * log */ private final static Log log = LogFactory.getLog(TimeHandler.class); /** * 对于执行时间超过指定毫秒,日志级别为error * 单位:毫秒 * 默认值:200 */ private int error = 200; /** * 对于执行时间超过指定毫秒,日志级别为warn * 单位:毫秒 * 默认值:100 */ private int warn = 100; /** * 对于执行时间超过指定毫秒,日志级别为info * 单位:毫秒 * 默认值:50 */ private int info = 50; /** * Method invoke ... * * @param methodInvocation of type MethodInvocation * @return Object * @throws Throwable when */ public Object invoke(MethodInvocation methodInvocation) throws Throwable { long procTime = System.currentTimeMillis(); try { return methodInvocation.proceed(); } finally { procTime = System.currentTimeMillis() - procTime; String msg = "Process method " + methodInvocation.getMethod().getName() + " successful! Total time: " + procTime + " milliseconds!"; if (procTime > error) { if (log.isErrorEnabled()) log.error(msg); } else if (procTime > warn) { if (log.isWarnEnabled()) log.warn(msg); } else if (procTime > info) { if (log.isInfoEnabled()) log.info(msg); } else { if (log.isDebugEnabled()) log.debug(msg); } } } /** * Method setError sets the error of this TimeHandler object. * * @param error the error of this TimeHandler object. */ public void setError(int error) { this.error = error; } /** * Method setWarn sets the warn of this TimeHandler object. * * @param warn the warn of this TimeHandler object. */ public void setWarn(int warn) { this.warn = warn; } /** * Method setInfo sets the info of this TimeHandler object. * * @param info the info of this TimeHandler object. */ public void setInfo(int info) { this.info = info; } }
然后我们可以在Spring中配置
<!-- Dao方法处理时间 --> <bean id="daoTimeHandler" class="TimeHandler"/> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <value>*Dao</value> </property> <property name="interceptorNames"> <list> <value>daoTimeHandler</value> </list> </property> </bean>
以上在运行时就可以在每个*Dao执行后记录该操作的使用时间。