通過攔截器來統計每個action的執行時間

來源:互聯網
上載者:User

struts2中已經有此攔截器了,但是這個攔截器的配置太麻煩,還要配置是否開啟和日誌的層級。本人認為太複雜,沒有必要。

統計每個action的執行時間,在測試開發的過程中需要用到。所以將此攔截器的代碼簡化,並將log4j的記錄層級提高到info。一旦測試通過在實際的生產環境中就直接將此攔截器從設定檔中去掉即可。詳細的java代碼如下:

  1. package com.work.core.interceptor;
  2. /*
  3.  * Copyright (c) 2002-2006 by OpenSymphony
  4.  * All rights reserved.
  5.  */
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import com.opensymphony.xwork2.ActionInvocation;
  9. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
  10. /**
  11.  * Timer簡化版。
  12.  * @author wangmj
  13.  */
  14. public class TimerInterceptor extends AbstractInterceptor {
  15.     /**
  16.      * 
  17.      */
  18.     private static final long serialVersionUID = 6017311502566041661L;
  19.     private static final Log log = LogFactory.getLog(TimerInterceptor.class);
  20.     public String intercept(ActionInvocation invocation) throws Exception {
  21.         long startTime = System.currentTimeMillis();//計算開始日期
  22.         String result = invocation.invoke();
  23.         long executionTime = System.currentTimeMillis() - startTime;
  24.         StringBuffer message = new StringBuffer(100);
  25.         message.append("Executed action [");
  26.         String namespace = invocation.getProxy().getNamespace();
  27.         if ((namespace != null) && (namespace.trim().length() > 0)) {
  28.             message.append(namespace).append("/");
  29.         }
  30.         message.append(invocation.getProxy().getActionName());
  31.         message.append("!");
  32.         message.append(invocation.getProxy().getMethod());
  33.         message.append("] took ").append(executionTime).append(" ms.");
  34.         if (log.isInfoEnabled()) {
  35.             log.info(message.toString());
  36.         }
  37.         return result;
  38.     }
  39. }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.