springboot项目如何使用切面记录用户操作日志

 更新时间:2022年10月31日 12:08:13   作者:WoddenFish  
这篇文章主要介绍了springboot项目如何使用切面记录用户操作日志,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

1、引入springboot-aop集成jar

Spring-boot-start-aop

2、application.yml中启用声明

#spring配置
spring:
  #切面启用
  aop:
    proxy-target-class: true
    auto: true

3、自定义一个拦截controller的注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定义注解,拦截controller
 */
 
@Target({ElementType.PARAMETER, ElementType.METHOD})//作用在参数和方法上
@Retention(RetentionPolicy.RUNTIME)//运行时注解
@Documented//表明这个注解应该被 javadoc工具记录
public @interface SystemControllerLog {
    String description() default "";
}

4、自定义一个拦截service的注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定义注解,拦截service
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}

5、定义日志记录切面

package cn.annotation;
 
import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description: 切点类
 */
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用于把日志保存数据库,实际项目入库采用队列做异步
    @Resource
    private ActionService actionService;
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service层切点
    @Pointcut("@annotation(cn.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }
 
    //Controller层切点
    @Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }
 
    /**
     * @Description  前置通知  用于拦截Controller层记录用户的操作
     * @date 2018年9月3日 10:38
     */
 
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) session.getAttribute("user");
 
        String ip = IpUtils.getIpAddr(request);
 
        try {
            //*========控制台输出=========*//
            System.out.println("==============前置通知开始==============");
            System.out.println("请求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
            System.out.println("请求人:"+user.getUsername());
            System.out.println("请求ip:"+ip);
 
            //*========数据库日志=========*//
            Action action = new Action();
            action.setActionDes(getControllerMethodDescription(joinPoint));
            action.setActionType("0");
            action.setActionIp(ip);
            action.setUserId(user.getId());
            action.setActionTime(new Date());
            //保存数据库
            actionService.add(action);
 
        }catch (Exception e){
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}",e.getMessage());
        }
    }
 
    /**
     * @Description  异常通知 用于拦截service层记录异常日志
     * @date 2018年9月3日 下午5:43
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) session.getAttribute("user");
        //获取请求ip
        String ip = IpUtils.getIpAddr(request);
        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            /*========控制台输出=========*/
            System.out.println("=====异常通知开始=====");
            System.out.println("异常代码:" + e.getClass().getName());
            System.out.println("异常信息:" + e.getMessage());
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("请求人:" + user.getUsername());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
            /*==========数据库日志=========*/
            Action action = new Action();
            action.setActionDes(getServiceMethodDescription(joinPoint));
            action.setActionType("1");
            action.setUserId(user.getId());
            action.setActionIp(ip);
            action.setActionTime(new Date());
            //保存到数据库
            actionService.add(action);
        }catch (Exception ex){
            //记录本地异常日志
            logger.error("==异常通知异常==");
            logger.error("异常信息:{}", ex.getMessage());
        }
    }
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于service层注解
     * @date 2018年9月3日 下午5:05
     */
    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;
    }
 
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     * @date 2018年9月3日 上午12:01
     */
    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;
    }
}

6、开始使用

1)@SystemControllerLog(description = "")

注解加在控制器中方法上面,括号里写上操作描述

2)用于监控service异常,可以不使用

@SystemServiceLog(description = "")

注解加在service层方法上面,括号里写上操作描述

(此处为AOP拦截Service记录异常信息。方法不需要加try-catch)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • logback 自定义Pattern模板教程

    logback 自定义Pattern模板教程

    这篇文章主要介绍了logback 自定义Pattern模板教程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 详解如何使用Mybatis的拦截器

    详解如何使用Mybatis的拦截器

    MyBatis 拦截器是 MyBatis 提供的一个强大特性,它允许你在 MyBatis 执行其核心逻辑的关键节点插入自定义逻辑,从而改变 MyBatis 的默认行为,本文给大家详细介绍了如何使用Mybatis的拦截器,需要的朋友可以参考下
    2024-03-03
  • Java非侵入式API接口文档工具apigcc用法详解

    Java非侵入式API接口文档工具apigcc用法详解

    这篇文章主要介绍了Java非侵入式API接口文档工具apigcc用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Java上传文件进度条的实现方法(附demo源码下载)

    Java上传文件进度条的实现方法(附demo源码下载)

    这篇文章主要介绍了Java上传文件进度条的实现方法,可简单实现显示文件上传比特数及进度的功能,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2015-12-12
  • Springboot使用zxing实现二维码生成和解析

    Springboot使用zxing实现二维码生成和解析

    ZXing支持各种条形码,二维码扫描,由多个模块组成, 而且支持PC端,移动端,本文将利用zxing实现二维码生成和解析,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-10-10
  • java 画pdf用itext调整表格宽度、自定义各个列宽的方法

    java 画pdf用itext调整表格宽度、自定义各个列宽的方法

    这篇文章主要介绍了java 画pdf用itext调整表格宽度、自定义各个列宽的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • 线程池运用不当引发的一次线上事故解决记录分析

    线程池运用不当引发的一次线上事故解决记录分析

    遇到了一个比较典型的线上问题,刚好和线程池有关,另外涉及到死锁、jstack命令的使用、JDK不同线程池的适合场景等知识点,同时整个调查思路可以借鉴,特此记录和分享一下
    2024-01-01
  • Spring Boot使用GridFS实现文件的上传和下载方式

    Spring Boot使用GridFS实现文件的上传和下载方式

    这篇文章主要介绍了Spring Boot使用GridFS实现文件的上传和下载方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • 详解PowerDesigner之CDM、PDM、SQL之间转换

    详解PowerDesigner之CDM、PDM、SQL之间转换

    这篇文章主要介绍了详解PowerDesigner之CDM、PDM、SQL之间转换的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
    2017-10-10
  • maven-compiler-plugin版本指定方式

    maven-compiler-plugin版本指定方式

    这篇文章主要介绍了maven-compiler-plugin版本指定方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01

最新评论