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

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

创建ActionLogAop接口

在这里插入图片描述

package com.greentranboot.common;

import java.lang.annotation.*;

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

    String value() default "";

}

创建ActionLogAspect拦截类

拦截并存入数据库
在这里插入图片描述

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(“标签说明”)**

在这里插入图片描述

数据库结构

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

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

结果测试

在这里插入图片描述

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;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值