自定义注解监控接口并记录操作日志到数据库

java 复制代码
package io.renren.ascept;

import io.annotation.LogOperation;
import io.common.utils.HttpContextUtils;
import io.common.utils.IpUtils;
import io.common.utils.JsonUtils;
import io.entity.TokenEntity;
import io.renren.entity.mianchong.ApiLogOperationEntity;
import io.renren.enums.OperationStatusEnum;
import io.renren.service.TokenService;
import io.renren.service.mianchong.ApiLogOperationService;
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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @describe 记录操作日志
 */
@Aspect
@Component
public class LogOperationAspect {
    @Resource
    private ApiLogOperationService apiLogOperationService;
    @Resource
    private TokenService tokenService;

    @Pointcut("@annotation(io.renren.annotation.LogOperation)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        try {
            //执行方法
            Object result = point.proceed();
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            saveLog(point, time, OperationStatusEnum.SUCCESS.value());
            return result;
        } catch (Exception e) {
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            saveLog(point, time, OperationStatusEnum.FAIL.value());
            throw e;
        }
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time, Integer status) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes());
        LogOperation annotation = method.getAnnotation(LogOperation.class);

        ApiLogOperationEntity log = new ApiLogOperationEntity();
        if (annotation != null) {
            //注解上的描述
            log.setOperation(annotation.value());
        }

        log.setStatus(status);
        log.setRequestTime((int) time);

        //请求相关信息
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        assert request != null;

        //客户端ip
        log.setIp(IpUtils.getClientIpAddress(request));

        //从header中获取token
        String token = request.getHeader("token");
        //token为空
        if (StringUtils.isBlank(token)) {
            log.setUserAgent("未登录操作");
        } else {
            //查询token信息
            TokenEntity tokenEntity = tokenService.getByToken(token);
            //登录用户信息
            log.setUserAgent(tokenEntity.getUserId().toString());
        }
        log.setRequestUri(request.getRequestURI());
        log.setRequestMethod(request.getMethod());

        //请求参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JsonUtils.toJsonString(args[0]);
            log.setRequestParams(params);
        } catch (Exception ignored) {
        }

        log.setCreateDate(new Date());
        //保存到DB
        apiLogOperationService.save(log);
    }
}
java 复制代码
package io.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 操作日志注解
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperation {

    String value() default "";
}

使用方法

java 复制代码
@PostMapping("xxxxx")
    @LogOperation("接口描述")
    public ResponseEntity<?> xxxxxxxx(@RequestBody DTO dto) throws IOException {
    ..............
    }

操作日志表:

sql 复制代码
CREATE TABLE `db_name`.`log_operation`  (
  `id` bigint(0) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'id',
  `operation` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户操作',
  `request_uri` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '请求URI',
  `request_method` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '请求方式',
  `request_params` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '请求参数',
  `request_time` int(0) UNSIGNED NOT NULL COMMENT '请求时长(毫秒)',
  `user_agent` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户代理',
  `ip` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '操作IP',
  `status` tinyint(0) UNSIGNED NOT NULL COMMENT '状态  0:失败   1:成功',
  `creator_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户名',
  `creator` bigint(0) NULL DEFAULT NULL COMMENT '创建者',
  `create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `idx_create_date`(`create_date`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '操作日志' ROW_FORMAT = Dynamic;
相关推荐
caihuayuan46 分钟前
鸿蒙AI开发:10-多模态大模型与原子化服务的集成
java·大数据·sql·spring·课程设计
沉到海底去吧Go12 分钟前
软件工具:批量图片区域识别+重命名文件的方法,发票识别和区域选择方法参考,基于阿里云实现
数据库·阿里云·云计算
张哈大18 分钟前
【 Redis | 实战篇 秒杀优化 】
java·数据库·redis·笔记·缓存
Musennn20 分钟前
MySQL多条件查询深度解析
大数据·数据库·mysql
低维歌者24 分钟前
python训练营day27
java·开发语言·python
大帅不是我33 分钟前
Python多进程编程执行任务
java·前端·python
purrrew1 小时前
【Java ee初阶】jvm(3)
java·jvm
Hello World......3 小时前
互联网大厂Java面试:从Spring到微服务的全面探讨
java·spring boot·spring cloud·微服务·面试·技术栈·互联网大厂
伤不起bb4 小时前
MySQL 高可用
linux·运维·数据库·mysql·安全·高可用
拾贰_C4 小时前
【SpringBoot】MyBatisPlus(MP | 分页查询操作
java·spring boot·后端·spring·maven·apache·intellij-idea