springcloud 定义切面实现对请求操作记录日志,方便后面分析接口详情

Posted 不负前行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud 定义切面实现对请求操作记录日志,方便后面分析接口详情相关的知识,希望对你有一定的参考价值。

  1 package com.idoipo.infras.gateway.open.config;
  2 
  3 import com.alibaba.fastjson.JSON;
  4 import com.alibaba.fastjson.JSONObject;
  5 import com.idoipo.infras.gateway.open.model.InvokeLogModel;
  6 import com.idoipo.infras.gateway.open.service.IInvokeLogService;
  7 import org.aspectj.lang.ProceedingJoinPoint;
  8 import org.aspectj.lang.annotation.Around;
  9 import org.aspectj.lang.annotation.Aspect;
 10 import org.aspectj.lang.annotation.Pointcut;
 11 import org.slf4j.Logger;
 12 import org.slf4j.LoggerFactory;
 13 import org.springframework.beans.factory.annotation.Autowired;
 14 import org.springframework.context.annotation.Configuration;
 15 import org.springframework.web.context.request.RequestAttributes;
 16 import org.springframework.web.context.request.RequestContextHolder;
 17 import org.springframework.web.context.request.ServletRequestAttributes;
 18 
 19 import javax.servlet.http.HttpServletRequest;
 20 import java.lang.reflect.Field;
 21 import java.util.Date;
 22 import java.util.HashMap;
 23 import java.util.Map;
 24 
 25 /**
 26  * Create by liping on 2018/8/20
 27  */
 28 @Aspect
 29 @Configuration//定义一个切面
 30 public class LogRecodeAspect {
 31 
 32     private static final Logger logger = LoggerFactory.getLogger(LogRecodeAspect.class);
 33 
 34     @Autowired
 35     IInvokeLogService invokeLogService;
 36 
 37     // 定义切点Pointcut
 38     @Pointcut("execution(public * com.idoipo.infras.gateway.open.controller..*.*(..))")
 39     public void excudeService() {
 40     }
 41 
 42     @Around("excudeService()")
 43     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
 44         RequestAttributes ra = RequestContextHolder.getRequestAttributes();
 45         ServletRequestAttributes sra = (ServletRequestAttributes) ra;
 46         HttpServletRequest request = sra.getRequest();
 47         String url = request.getRequestURI();
 48         String method = request.getMethod();
 49         String queryString = request.getQueryString();
 50         Object[] args = pjp.getArgs();
 51         String params = "";
 52         String invokeUser = "";
 53         int userFlag = 1;
 54         //获取请求参数集合并进行遍历拼接
 55         if(args.length>0){
 56             if("POST".equals(method)){
 57                 Object object = args[0];
 58                 Map map = getKeyAndValue(object); 69                 params = JSON.toJSONString(map);
 70             }else if("GET".equals(method)){
 71                 if(null!=queryString&&""!=queryString){
 72                     String[] paramArray = queryString.split("&");
 73                     for(String param : paramArray){
 74                         String[] keyValue = param.split("=");
 75                         String key = keyValue[0];
 76                         if(keyValue[0].equals("user")){
 77                             invokeUser = keyValue[1];
 78                         }else if(keyValue[0].equals("userFlag"))
 79                             userFlag = Integer.parseInt(keyValue[1]);
 80                     }
 81                     params = queryString;
 82                 }
 83 
 84             }
 85         }
 86         logger.info("请求开始地址={},类型={},参数={}:",url,method,params);
 87         Date startTime = new Date();
 88         // result的值就是被拦截方法的返回值
 89         Object result = pjp.proceed();
 90         boolean responseResult = false;
 91         String response = JSONObject.toJSONString(result);
102         logger.info("请求结束===返回值={}:" + response);
103         Date endTime = new Date();
104         InvokeLogModel invokeLogModel = new InvokeLogModel();
105         invokeLogModel.setInterfaceName(url);
106         invokeLogModel.setInterfaceMethod(method);
107 
108         invokeLogModel.setInvokeStartTime(startTime);
109         invokeLogModel.setRequestParam(params);
110 
111         invokeLogModel.setResponseResult(responseResult);
112         invokeLogModel.setInvokeEndTime(endTime);115         invokeLogService.insertInvokerLog(invokeLogModel);
116         return result;
117     }
118 
119     public static Map<String, Object> getKeyAndValue(Object obj) {
120         Map<String, Object> map = new HashMap<>();
121         // 得到类对象
122         Class userCla = obj.getClass();
123         /* 得到类中的所有属性集合 */
124         Field[] fs = userCla.getDeclaredFields();
125         for (int i = 0; i < fs.length; i++) {
126             Field f = fs[i];
127             f.setAccessible(true); // 设置些属性是可以访问的
128             Object val ;
129             try {
130                 val = f.get(obj);
131                 // 得到此属性的值
132                 map.put(f.getName(), val);// 设置键值
133             } catch (IllegalArgumentException e) {
134                 logger.error("解析参数异常",e);
135             } catch (IllegalAccessException e) {
136                 logger.error("解析参数异常",e);
137             }
138 
139         }
140         return map;
141     }
142 }
package com.idoipo.infras.gateway.open.model;

import java.util.Date;

public class InvokeLogModel {

    //自增id
    private int id;
    //接口名
    private String interfaceName;
    //接口方法类型 GET or POST之类的
    private String interfaceMethod;
    //调用接口开始的时间
    private Date invokeStartTime;
    //调用接口结束的时间
    private Date invokeEndTime;
    //接口请求参数
    private String requestParam;
    //是否有响应值
    private Boolean responseResult;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    public String getInterfaceName() {
        return interfaceName;
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }

    public String getInterfaceMethod() {
        return interfaceMethod;
    }

    public void setInterfaceMethod(String interfaceMethod) {
        this.interfaceMethod = interfaceMethod;
    }

    public Date getInvokeStartTime() {
        return invokeStartTime;
    }

    public void setInvokeStartTime(Date invokeStartTime) {
        this.invokeStartTime = invokeStartTime;
    }

    public Date getInvokeEndTime() {
        return invokeEndTime;
    }

    public void setInvokeEndTime(Date invokeEndTime) {
        this.invokeEndTime = invokeEndTime;
    }

    public String getRequestParam() {
        return requestParam;
    }

    public void setRequestParam(String requestParam) {
        this.requestParam = requestParam;
    }

    public Boolean getResponseResult() {
        return responseResult;
    }

    public void setResponseResult(Boolean responseResult) {
        this.responseResult = responseResult;
    }

    @Override
    public String toString() {
        return "InvokeLogModel{" +
                "id=" + id +
                ", interfaceName=‘" + interfaceName + ‘‘‘ +
                ", interfaceMethod=‘" + interfaceMethod + ‘‘‘ +
                ", invokeStartTime=" + invokeStartTime +
                ", invokeEndTiem=" + invokeEndTime +
                ", requestParam=‘" + requestParam + ‘‘‘ +
                ", responseResult=" + responseResult +
                ‘}‘;
    }
}

 

以上是关于springcloud 定义切面实现对请求操作记录日志,方便后面分析接口详情的主要内容,如果未能解决你的问题,请参考以下文章

springboot通过切面编程实现系统请求操作日志记录

SpringCloud请求响应数据转换

SpringCloud快捷创建注解切面

切面+自定义注解的一些玩法

通过切面将请求日志记录到数据库

AOP实现日志记录功能