SpringBoot引入AOP记录用户日志

SpringBoot引入AOP记录用户日志

效果

2020-07-28 09:32:16-[INFO]-[] 切面--前置通知
【请求方法:com.resource.ResourceManagerController.getResourceRel】
【方法描述:根据ID查询资源信息】
【请求人:admin】
【请求IP:169.254.124.120】
【参数:["1281069637315870720"]】

前提

  • 工程为SpringBoot工程

application.yml配置

spring:
  aop:
    proxy-target-class: true
    auto: true

自定义注解

  • 控制层SystemControllerLog
import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemControllerLog {
    String description() default "";
}
  • 业务层SystemServiceLog
import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}

切面【注:复制粘贴报错的方法根据自己已有的工具类进行改造

  • SystemLogAspect
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {

    //Service层切点
    @Pointcut("@annotation(com.common.annotate.SystemServiceLog)")
    public void serviceAspect() {
    }

    //Controller层切点
    @Pointcut("@annotation(com.common.annotate.SystemControllerLog)")
    public void controllerAspect() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            String user_name = "unKnow";
            String ip = "unKnow";

            if (request != null && request.getSession() != null) {
                user_name = CasJsonUtil.getLoginNo(request.getSession());
            }
            if (request != null) {
                ip = getIpAddress(request);
            }

            Object[] args = null;
            Object[] arguments = null;

            if (joinPoint != null) {
                args = joinPoint.getArgs();
            }
            if (args != null) {
                arguments = new Object[args.length];
            }

            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                    continue;
                }
                arguments[i] = args[i];
            }
            String params = JSONObject.toJSONString(arguments);


            LogUtils.restLogger.info("切面--前置通知\r\n" + "{}", "【请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()) + "】\r\n【方法描述:" + getControllerMethodDescription(joinPoint) + "】\r\n【请求人:" + user_name + "】\r\n【请求IP:" + ip + "】\r\n【参数:" + params + "】");
        } catch (Exception e) {
            LogUtils.restLogger.info("切面--前置通知异常" + "{}", e.getMessage());
        }
    }


    /**
     * 异常通知 用于拦截service层记录异常日志
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String user_name = "unKnow";
            String ip = "unKnow";

            if (request != null && request.getSession() != null) {
                user_name = CasJsonUtil.getLoginNo(request.getSession());
            }
            if (request != null) {
                ip = getIpAddress(request);
            }

            Object[] args = null;
            Object[] arguments = null;

            if (joinPoint != null) {
                args = joinPoint.getArgs();
            }
            if (args != null) {
                arguments = new Object[args.length];
            }
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                    continue;
                }
                arguments[i] = args[i];
            }
            String params = JSONObject.toJSONString(arguments);
            LogUtils.restLogger.info("切面--异常通知\r\n" + "{}", "【异常代码:" + e.getClass().getName() + "】\r\n【异常信息:" + e.getMessage() + "】\r\n【异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()") + "】\r\n【方法描述:" + getServiceMethodDescription(joinPoint) + "】\r\n【请求人:" + user_name + "】\r\n【请求IP:" + ip + "】\r\n【请求参数:" + params + "】");
        } catch (Exception ex) {
            LogUtils.restLogger.info("切面--异常通知--异常" + "{}", e.getMessage());
        }
    }


    /**
     * 获取注解中对方法的描述信息 用于service层注解
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }


    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }

    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")
                    || ip.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (inet != null) {
                    ip = inet.getHostAddress();
                }
            }
        }

        // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}

使用

  • 控制类中
@RequestMapping("/getResourceRel")
@ResponseBody
@SystemControllerLog(description = "根据ID查询资源信息")
public ServiceRes<List<MalltRightsResourceRel>> getResourceRel(String resourceId) {
    return null;
}
  • 业务层中
@Override
@SystemServiceLog(description = "查询资源是否打包")
public BusiResp<List<MalltRightsResourceRel>> getResourceRel(String resourceId) {
    return null;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值