springboot自定义标签实现AOP切面记录操作日志

一言以蔽之创建ActionLogAop接口、创建ActionLogAspect拦截类、给接口打标签@ActionLogAop(“标签说明”)

创建ActionLogAop接口

springboot自定义标签实现AOP切面记录操作日志_第1张图片

package com.greentranboot.common;

import java.lang.annotation.*;

/**
 * @author wj
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionLogAop {

    String value() default "";

}

创建ActionLogAspect拦截类

拦截并存入数据库
springboot自定义标签实现AOP切面记录操作日志_第2张图片

package com.greentranboot.common;

import com.greentranboot.manager.RequestManager;
import com.greentranboot.manager.UserManager;
import com.greentranboot.service.ActionLogService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import com.greentranboot.pojo.ActionLog;

/**
 * @author wj
 */
@Aspect
@Component
public class ActionLogAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ActionLogService actionLogService;

    //     拦截包下面的所有类的所有方法,配置参考https://www.cnblogs.com/Timeouting-Study/p/15179264.html
    @Pointcut("execution(* com.greentranboot.controller.admin.*.*(..)) || execution(* com.LvChuangNews.controller..*.*(..))")
    public void cusTomLogPointcut() {
    }


    @Around("cusTomLogPointcut()")
    public Object Around(ProceedingJoinPoint point) throws Throwable {
        Object object = point.proceed();
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //获取操作
        ActionLogAop operation = method.getAnnotation(ActionLogAop.class);
        if (operation != null) {
            ActionLog actionLog = new ActionLog();
            actionLog.setLogMethodZh(operation.value());//接口说明文字

            //获取请求的类名
            String className = point.getTarget().getClass().getName();
            //获取请求的方法名
            String methodName = method.getName();
            String methodStr = (className + "." + methodName);
            actionLog.setLogMethodEn(methodStr);

            // 数据转字符,并参数保留100字
            String allParams = StringUtils.join(point.getArgs(),';');
            allParams=StringUtils.abbreviate(allParams,100);
            actionLog.setLogMethodParameter(allParams);

            //获取用户ip地址
            actionLog.setLogIp(RequestManager.currentIP());
            //时间
            actionLog.setLogTime(new Date());
            //写入数据库

            //用户ID、用户名
            actionLog.setLogUserId(UserManager.currentUserId());
            actionLog.setLogUserName(UserManager.currentUserName());

            actionLogService.addActionLog(actionLog);

            logger.debug("行为日志: " + methodName);
        }

        return object;
    }


}

给接口打标签@ActionLogAop(“标签说明”)**

springboot自定义标签实现AOP切面记录操作日志_第3张图片

数据库结构

DROP TABLE IF EXISTS `action_log`;
CREATE TABLE `action_log` (
  `log_id` bigint NOT NULL AUTO_INCREMENT,
  `log_method_zh` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法中文',
  `log_method_en` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法英文',
  `log_method_parameter` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '参数前100字',
  `log_ip` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'ipv6长度',
  `log_user_id` varchar(50) DEFAULT NULL,
  `log_user_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `log_time` datetime DEFAULT NULL,
  PRIMARY KEY (`log_id`),
  UNIQUE KEY `dat_log_log_id_uindex` (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Mybatis实体类xml

根据以上面数据表结构生成即可

结果测试

springboot自定义标签实现AOP切面记录操作日志_第4张图片

swagger注释作为操作日志写入

package com.greentranboot.common;

import com.greentranboot.manager.RequestManager;
import com.greentranboot.manager.UserManager;
import com.greentranboot.pojo.ActionLog;
import com.greentranboot.service.ActionLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;




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

@Aspect
@Component

public class ActionLogAspect {


    @Autowired
    private ActionLogService actionLogService;

    // 拦截包下面的所有类的所有方法,配置参考https://www.cnblogs.com/Timeouting-Study/p/15179264.html
    @Pointcut("execution(* com.greentranboot.controller.admin.*.*(..)) || execution(* com.LvChuangNews.controller..*.*(..))")

    public void aspectForPub() {
    }

    @Around("aspectForPub()")
    public Object logRecored(ProceedingJoinPoint point) throws Throwable {
        Object object = point.proceed();


        Long start = System.currentTimeMillis();
        Api api = (Api) (point.getSignature().getDeclaringType().getAnnotation(Api.class));
        if (api != null) {
            ActionLog actionLog = new ActionLog();

            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            ApiOperation operation = method.getAnnotation(ApiOperation.class);

            actionLog.setLogMethodZh(operation.value());//接口说明文字

            //获取请求的类名
            String className = point.getTarget().getClass().getName();
            //获取请求的方法名
            String methodName = method.getName();
            String methodStr = (className + "." + methodName);
            actionLog.setLogMethodEn(methodStr);

            // 数据转字符,并参数保留100字
            String allParams = StringUtils.join(point.getArgs(),';');
            allParams=StringUtils.abbreviate(allParams,100);
            actionLog.setLogMethodParameter(allParams);

            //获取用户ip地址
            actionLog.setLogIp(RequestManager.currentIP());
            //时间
            actionLog.setLogTime(new Date());
            //写入数据库

            //用户ID、用户名
            actionLog.setLogUserId(UserManager.currentUserId());
            actionLog.setLogUserName(UserManager.currentUserName());
            //方法用时
            long spendtime =System.currentTimeMillis() - start;
            actionLog.setLog_spend_time((int)spendtime);
            actionLogService.addActionLog(actionLog);
        }
        return object;
    }
}

你可能感兴趣的:(java,spring,boot,java,spring)