struts2中已经有此拦截器了,但是这个拦截器的配置太麻烦,还要配置是否开启和日志的级别。本人认为太复杂,没有必要。
统计每个action的执行时间,在测试开发的过程中需要用到。所以将此拦截器的代码简化,并将log4j的日志级别提高到info。一旦测试通过在实际的生产环境中就直接将此拦截器从配置文件中去掉即可。详细的java代码如下:
- package com.work.core.interceptor;
- /*
- * Copyright (c) 2002-2006 by OpenSymphony
- * All rights reserved.
- */
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- /**
- * Timer简化版。
- * @author wangmj
- */
- public class TimerInterceptor extends AbstractInterceptor {
- /**
- *
- */
- private static final long serialVersionUID = 6017311502566041661L;
- private static final Log log = LogFactory.getLog(TimerInterceptor.class);
- public String intercept(ActionInvocation invocation) throws Exception {
- long startTime = System.currentTimeMillis();//计算开始日期
- String result = invocation.invoke();
- long executionTime = System.currentTimeMillis() - startTime;
- StringBuffer message = new StringBuffer(100);
- message.append("Executed action [");
- String namespace = invocation.getProxy().getNamespace();
- if ((namespace != null) && (namespace.trim().length() > 0)) {
- message.append(namespace).append("/");
- }
- message.append(invocation.getProxy().getActionName());
- message.append("!");
- message.append(invocation.getProxy().getMethod());
- message.append("] took ").append(executionTime).append(" ms.");
- if (log.isInfoEnabled()) {
- log.info(message.toString());
- }
- return result;
- }
- }