RunAspect.java 7.59 KB
package com.dituhui.mp.aop;

import com.alibaba.fastjson.JSONObject;
import com.dituhui.mp.enums.StatusCodeEnum;
import com.dituhui.mp.exception.BusinessException;
import com.dituhui.mp.log.LogsAnnotation;
import com.dituhui.mp.log.PlatformLogger;
import com.dituhui.mp.pojo.CurrentUser;
import com.dituhui.mp.pojo.PlatformUser;
import com.dituhui.mp.pojo.WebResult;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Calendar;

/**
 * 处理日志
 */
@Aspect
@Component
@Order(1)
public class RunAspect {

    /**
     * 日志级别
     */
    private final static String ri = "info", re = "error";

    @Autowired
    private PlatformLogger platformLogger;

    @Autowired
    private CurrentUser currentUser;

    /**
     * 参数最大长度
     */
    private final static int argLen = 3000;

    /**
     * 控制层运行日志
     *
     * @param p 切面点
     * @return obj
     */
    @Deprecated
    @Around("execution(* com.dituhui.mp.*.controller.*.*(..))")
    public Object webLog(ProceedingJoinPoint p) {
        // 请求参数
        StringBuilder sb = new StringBuilder();
        try {
            // 记录参数类型及值
            for (int i = 0; i < p.getArgs().length; i++) {
                try {
                    if (p.getArgs()[i] != null && StringUtils.isNotEmpty(p.getArgs()[i].getClass().getSimpleName())) {
                        // 存在参数类型才记录
                        sb.append(",");
                        sb.append(p.getArgs()[i].getClass().getSimpleName());
                        sb.append(":");
                        sb.append(p.getArgs()[i]);
                    }
                } catch (Exception e) {
                    // 参数获取失败
                    sb.append("args error(").append(p.getArgs().length).append("):").append(i + 1);
                }
            }
        } catch (Exception e) {
            // 参数获取失败
            sb.append("args error(").append(p.getArgs().length).append("):未知错误");
        }
        PlatformUser user = currentUser.getPlatformUser();
        // 返回类型
        Class<?> returnType = null;
        // 日志对象
        JSONObject jObj = new JSONObject();
        if (sb.toString().length() > 0) {
            // 记录参数,如果超出长度则截取
            if (sb.length() > argLen) {
                jObj.put("params", sb.substring(1, argLen) + "...");
            } else {
                jObj.put("params", sb.substring(1));
            }
        }
        jObj.put("bID", user.getBid());
        if (StringUtils.isNotEmpty(user.getToken())) {
            jObj.put("tk", user.getToken());
        }
        jObj.put("sourceIp", user.getClientIP());
        jObj.put("t", user.getT());
        // 操作时间,operation time
        jObj.put("ot", Calendar.getInstance().getTime());
        // 日志开始时间
        long beginTime = System.currentTimeMillis();
        try {
            MethodSignature ms = (MethodSignature) p.getSignature();
            returnType = ms.getReturnType();
            Object result = p.proceed();
            jObj.put("level", ri);
            // 耗时,time counting
            jObj.put("elapse", System.currentTimeMillis() - beginTime);
            platformLogger.info(ms.getMethod(), jObj);
            currentUser.removePlatformUser();
            return result;
        } catch (Throwable t) {
            jObj.put("level", re);
            jObj.put("elapse", System.currentTimeMillis() - beginTime);
            platformLogger.error(t, jObj);
            currentUser.removePlatformUser();
            // 判断是否为业务异常
            if (t instanceof BusinessException) {
                StatusCodeEnum codeEnum = ((BusinessException) t).codeEnum;
                return WebResult.failed(codeEnum);
            } else {
                if (returnType != null && WebResult.class.getSimpleName().equals(returnType.getSimpleName())) {
                    // 指定返回类型
                    return WebResult.failed(StatusCodeEnum.SYSTEM_UNKNOWN_ERROR);
                }
            }
        }
        currentUser.removePlatformUser();
        return WebResult.failed(StatusCodeEnum.SYSTEM_UNKNOWN_ERROR);
    }

    /**
     * 服务模块运行日志
     *
     * @param p 切面点
     * @return obj
     * @throws Throwable throwable
     */
    @Around("execution(* com.dituhui.mp.*.service.*.*(..)) || execution(* com.dituhui.mp.*.service.*.service.impl.*.*(..))"
            + "||execution(* com.dituhui.mp.*.service.*.custom.service.*.*(..))")
    public Object serviceLog(ProceedingJoinPoint p) throws Throwable {
        PlatformUser user = currentUser.getPlatformUser();
        // 请求参数
        StringBuilder sb = new StringBuilder();
        try {
            // 记录参数类型及值
            for (int i = 0; i < p.getArgs().length; i++) {
                try {
                    if (p.getArgs()[i] != null && StringUtils.isNotEmpty(p.getArgs()[i].getClass().getSimpleName())) {
                        // 存在参数类型才记录
                        sb.append(",");
                        sb.append(p.getArgs()[i].getClass().getSimpleName());
                        sb.append(":");
                        sb.append(p.getArgs()[i]);
                    }
                } catch (Exception e) {
                    // 参数获取失败
                    sb.append("args error(").append(p.getArgs().length).append("):").append(i + 1);
                }
            }
        } catch (Exception e) {
            // 参数获取失败
            sb.append("args error(").append(p.getArgs().length).append("):未知错误");
        }
        // 日志对象
        JSONObject jObj = new JSONObject();
        if (sb.toString().length() > 0) {
            // 记录参数,如果超出长度则截取
            if (sb.length() > argLen) {
                jObj.put("params", sb.substring(1, argLen) + "...");
            } else {
                jObj.put("params", sb.substring(1));
            }
        }
        jObj.put("bID", user.getBid());
        if (StringUtils.isNotEmpty(user.getToken())) {
            jObj.put("tk", user.getToken());
        }
        jObj.put("sourceIp", user.getClientIP());
        jObj.put("t", user.getT());
        // 操作时间,operation time
        jObj.put("ot", Calendar.getInstance().getTime());
        // 日志开始时间
        long beginTime = System.currentTimeMillis();
        MethodSignature ms = (MethodSignature) p.getSignature();
        Method method = ms.getMethod();
        LogsAnnotation logsAnnotation = method.getAnnotation(LogsAnnotation.class);
        Object result;
        try {
            result = p.proceed();
        } catch (Throwable t) {
            jObj.put("level", re);
            jObj.put("elapse", System.currentTimeMillis() - beginTime);
            platformLogger.error(t, jObj, method);
            // 异常由最上层捕获,所以向上抛
            throw t;
        }
        jObj.put("level", ri);
        // 耗时,time counting
        jObj.put("elapse", System.currentTimeMillis() - beginTime);
        if (logsAnnotation == null || logsAnnotation.logSwitch()) {
            // 根据日志开关决定是否记录日志
            platformLogger.info(method, jObj);
        }
        return result;
    }

}