利用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. }  
posted on 2017-06-02 11:01  沐雨橙风丶  阅读(3931)  评论(0编辑  收藏  举报