kongzy
2023-12-08 ca5445257b1fdeceddf3fcc2dea18c442023aeb7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package com.gkhy.assess.framework.aop;
 
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import com.gkhy.assess.common.utils.StringUtils;
import com.gkhy.assess.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Aspect
@Component
@Slf4j
public class LogAspect {
    @Pointcut("execution(public * com.gkhy.assess.*.controller..*.*(..))")
    public void logPointCut(){
 
    }
 
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        StringBuffer requestURL = request.getRequestURL();
        JSONObject webLog = new JSONObject();
        String urlStr = request.getRequestURL().toString();
        webLog.put("basePath", StringUtils.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.put("ip", ServletUtil.getClientIP(request,null));
        webLog.put("method",request.getMethod());
        Object params=getParameter(method, joinPoint.getArgs());
        webLog.put("parameter",params);
        webLog.put("uri",request.getRequestURI());
        webLog.put("url",requestURL.toString());
        String userId=ShiroUtils.getUserId()!=null?String.valueOf(ShiroUtils.getUserId()):"";
        webLog.put("userId",userId);
        log.info(webLog.toString());
        Object result = joinPoint.proceed();
        if (result == null) {
            //如果切到了 没有返回类型的void方法,这里直接返回
            return null;
        }
        long endTime = System.currentTimeMillis();
        webLog.put("result",result);
        webLog.put("spendTime",endTime - startTime);
        log.info(webLog.toString());
        return result;
    }
 
    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String urlStr = request.getRequestURL().toString();
        log.error("@AfterThrowing异常通知:url={},出错了error_message={}", urlStr,e.getMessage());
    }
 
 
 
    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (StringUtils.isNotEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
 
}