利用spring AOP實現每個請求的日志輸出


前提條件:

除了spring相關jar包外,還需要引入aspectj包。

Xml代碼   收藏代碼
  1. <dependency>  
  2.         <groupId>org.aspectj</groupId>  
  3.         <artifactId>aspectjweaver</artifactId>  
  4.         <version>1.7.2</version>  
  5.     </dependency>  

 

 

 

要實現此功能,必須完成以下幾步:

1.在springmvc-servlet.xml中實現對AOP的支持

Xml代碼   收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.     xmlns:aop="http://www.springframework.org/schema/aop"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.     xsi:schemaLocation="     
  8.            http://www.springframework.org/schema/beans     
  9.            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd     
  10.            http://www.springframework.org/schema/context     
  11.            http://www.springframework.org/schema/context/spring-context-4.0.xsd    
  12.            http://www.springframework.org/schema/mvc     
  13.            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  14.            http://www.springframework.org/schema/aop   
  15.            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">  
  16.              
  17.     <aop:aspectj-autoproxy proxy-target-class="true"/>  
  18.     <bean class="com.yusj.interceptor.LogAspect" />  
  19. .  
  20. .  
  21. .  
  22. .  
  23. </beans>  

 

2.注解的方法實現Aspect

Java代碼   收藏代碼
  1. package com.yusj.core.interceptor;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8.   
  9. import org.aspectj.lang.JoinPoint;  
  10. import org.aspectj.lang.ProceedingJoinPoint;  
  11. import org.aspectj.lang.annotation.After;  
  12. import org.aspectj.lang.annotation.Around;  
  13. import org.aspectj.lang.annotation.Aspect;  
  14. import org.aspectj.lang.annotation.Before;  
  15. import org.slf4j.Logger;  
  16. import org.slf4j.LoggerFactory;  
  17. import org.springframework.web.context.request.RequestAttributes;  
  18. import org.springframework.web.context.request.RequestContextHolder;  
  19. import org.springframework.web.context.request.ServletRequestAttributes;  
  20.   
  21. import com.google.gson.Gson;  
  22.   
  23. /** 
  24.  *  
  25. * @ClassName: LogAspect  
  26. * @Description: 日志記錄AOP實現  
  27. * @author shaojian.yu 
  28. * @date 2014年11月3日 下午1:51:59  
  29.  */  
  30. @Aspect  
  31. public class LogAspect {  
  32.     private final Logger logger = LoggerFactory.getLogger(this.getClass());  
  33.   
  34.     private String requestPath = null ; // 請求地址  
  35.     private String userName = null ; // 用戶名  
  36.     private Map<?,?> inputParamMap = null ; // 傳入參數  
  37.     private Map<String, Object> outputParamMap = null; // 存放輸出結果  
  38.     private long startTimeMillis = 0; // 開始時間  
  39.     private long endTimeMillis = 0; // 結束時間  
  40.   
  41.     /** 
  42.      *  
  43.      * @Title:doBeforeInServiceLayer 
  44.      * @Description: 方法調用前觸發  
  45.      *  記錄開始時間  
  46.      * @author shaojian.yu  
  47.      * @date 2014年11月2日 下午4:45:53 
  48.      * @param joinPoint 
  49.      */  
  50.     @Before("execution(* com.yusj.controller..*.*(..))")  
  51.     public void doBeforeInServiceLayer(JoinPoint joinPoint) {  
  52.         startTimeMillis = System.currentTimeMillis(); // 記錄方法開始執行的時間  
  53.     }  
  54.   
  55.     /** 
  56.      *  
  57.      * @Title:doAfterInServiceLayer 
  58.      * @Description: 方法調用后觸發  
  59.      *  記錄結束時間 
  60.      * @author shaojian.yu  
  61.      * @date 2014年11月2日 下午4:46:21 
  62.      * @param joinPoint 
  63.      */  
  64.     @After("execution(* com.yusj.controller..*.*(..))")  
  65.     public void doAfterInServiceLayer(JoinPoint joinPoint) {  
  66.         endTimeMillis = System.currentTimeMillis(); // 記錄方法執行完成的時間  
  67.         this.printOptLog();  
  68.     }  
  69.   
  70.     /** 
  71.      *  
  72.      * @Title:doAround 
  73.      * @Description: 環繞觸發  
  74.      * @author shaojian.yu  
  75.      * @date 2014年11月3日 下午1:58:45 
  76.      * @param pjp 
  77.      * @return 
  78.      * @throws Throwable 
  79.      */  
  80.     @Around("execution(* com.yusj.controller..*.*(..))")  
  81.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
  82.         /** 
  83.          * 1.獲取request信息 
  84.          * 2.根據request獲取session 
  85.          * 3.從session中取出登錄用戶信息 
  86.          */  
  87.         RequestAttributes ra = RequestContextHolder.getRequestAttributes();  
  88.         ServletRequestAttributes sra = (ServletRequestAttributes)ra;  
  89.         HttpServletRequest request = sra.getRequest();  
  90.         // 從session中獲取用戶信息  
  91.         String loginInfo = (String) session.getAttribute("username");  
  92.         if(loginInfo != null && !"".equals(loginInfo)){  
  93.             userName = operLoginModel.getLogin_Name();  
  94.         }else{  
  95.             userName = "用戶未登錄" ;  
  96.         }  
  97.         // 獲取輸入參數  
  98.         inputParamMap = request.getParameterMap();  
  99.         // 獲取請求地址  
  100.         requestPath = request.getRequestURI();  
  101.           
  102.         // 執行完方法的返回值:調用proceed()方法,就會觸發切入點方法執行  
  103.         outputParamMap = new HashMap<String, Object>();  
  104.         Object result = pjp.proceed();// result的值就是被攔截方法的返回值  
  105.         outputParamMap.put("result", result);  
  106.           
  107.         return result;  
  108.     }  
  109.   
  110.     /** 
  111.      *  
  112.      * @Title:printOptLog 
  113.      * @Description: 輸出日志  
  114.      * @author shaojian.yu  
  115.      * @date 2014年11月2日 下午4:47:09 
  116.      */  
  117.     private void printOptLog() {  
  118.         Gson gson = new Gson(); // 需要用到google的gson解析包  
  119.         String optTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeMillis);  
  120.         logger.info("\n user:"+userName  
  121.                 +"  url:"+requestPath+"; op_time:" + optTime + " pro_time:" + (endTimeMillis - startTimeMillis) + "ms ;"  
  122.                 +" param:"+gson.toJson(inputParamMap)+";"+"\n result:"+gson.toJson(outputParamMap));  
  123.     }  
  124. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM