puzhibing
2023-02-26 8883d654f52171657b62aaec85027f29ef0a4dd0
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
package com.supersavedriving.user.core.common.aspect;
 
import com.alibaba.fastjson.JSONObject;
import com.supersavedriving.user.core.common.annotion.ServiceLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
 
@Aspect
@Component
public class ServiceLogAspect {
 
    Logger logger = LoggerFactory.getLogger("ServiceLog");
 
    /**
     * //切面点为标记了@ServiceLog注解的方法
     */
    @Pointcut("@annotation(com.supersavedriving.user.core.common.annotion.ServiceLog)")
    public void serviceLog(){
    }
 
 
    //环绕通知
    @Around("serviceLog()")
    @SuppressWarnings("unchecked")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long starTime = System.currentTimeMillis();
        //通过反射获取被调用方法的Class
        Class type = joinPoint.getSignature().getDeclaringType();
        //获取类名
        String typeName = type.getSimpleName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //获取参数列表
        Object[] args = joinPoint.getArgs();
        //参数Class的数组
        Class[] clazz = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            clazz[i] = args[i].getClass();
        }
        //通过反射获取调用的方法method
        Method method = type.getMethod(methodName, clazz);
        ServiceLog serviceLog = method.getAnnotation(ServiceLog.class);
        //获取方法的参数
        Parameter[] parameters = method.getParameters();
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            String name = parameter.getName();
            jsonObject.put(name, args[i]);
        }
        //执行结果
        //执行目标方法,获取执行结果
        Object res = joinPoint.proceed();
        logger.debug("调用{}.{}方法成功\n" +
                "接口名称:{}\n" +
                "接口地址:{}\n" +
                "耗时:{}ms\n" +
                "参数为:{}\n" +
                "返回结果:{}", typeName, methodName, serviceLog.name(), serviceLog.url(),
                (System.currentTimeMillis() - starTime), jsonObject.toJSONString(), JSONObject.toJSONString(res));
        //返回执行结果
        return res;
    }
}