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;
- }
- }