SpringBoot AOP 记录操作日志、异常日志

2022-06-24 15:23:50 浏览数 (1)

使用SpringBoot AOP 记录操作日志、异常日志

我们在做项目时经常需要对一些重要功能操作记录日志,方便以后跟踪是谁在操作此功能。在操作某些功能时也有可能会发生异常,但是每次发生异常要定位原因都要到服务器去查询日志才能找到,这样也不能对发生的异常进行统计。我们可以在需要的方法中增加记录日志的代码,和在每个方法中增加记录异常的代码,最终把记录的日志存到数据库中。

Spring AOP 的主要功能就是将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来。今天我们就来用springBoot Aop 来做日志记录

一、表结构

使用的数据库为 PostgreSql,不同数据库SQL存在差异,自行修改即可。

代码语言:javascript复制
-- 操作日志表
CREATE TABLE "public"."log_info" (
  "id" varchar(64) COLLATE "pg_catalog"."default" NOT NULL DEFAULT NULL::character varying,
  "module" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "type" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "message" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "req_param" text COLLATE "pg_catalog"."default",
  "res_param" text COLLATE "pg_catalog"."default",
  "take_up_time" int8,
  "user_id" varchar(64) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "user_name" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "method" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "uri" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "ip" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "version" varchar(64) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "create_time" timestamp(6) DEFAULT NULL::timestamp without time zone
);
COMMENT ON COLUMN "public"."log_info"."id" IS '主键id';
COMMENT ON COLUMN "public"."log_info"."module" IS '功能模块';
COMMENT ON COLUMN "public"."log_info"."type" IS '操作类型';
COMMENT ON COLUMN "public"."log_info"."message" IS '操作描述';
COMMENT ON COLUMN "public"."log_info"."req_param" IS '请求参数';
COMMENT ON COLUMN "public"."log_info"."res_param" IS '响应参数';
COMMENT ON COLUMN "public"."log_info"."take_up_time" IS '耗时';
COMMENT ON COLUMN "public"."log_info"."user_id" IS '操作用户id';
COMMENT ON COLUMN "public"."log_info"."user_name" IS '操作用户名称';
COMMENT ON COLUMN "public"."log_info"."method" IS '操作方面';
COMMENT ON COLUMN "public"."log_info"."uri" IS '请求url';
COMMENT ON COLUMN "public"."log_info"."ip" IS '请求IP';
COMMENT ON COLUMN "public"."log_info"."version" IS '版本号';
COMMENT ON COLUMN "public"."log_info"."create_time" IS '创建时间';
COMMENT ON TABLE "public"."log_info" IS '操作日志';

ALTER TABLE "public"."log_info" ADD CONSTRAINT "log_info_pkey" PRIMARY KEY ("id");


-- 异常信息表
CREATE TABLE "public"."log_error_info" (
  "id" varchar(64) COLLATE "pg_catalog"."default" NOT NULL DEFAULT NULL::character varying,
  "req_param" text COLLATE "pg_catalog"."default",
  "name" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "message" text COLLATE "pg_catalog"."default",
  "user_id" varchar(64) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "user_name" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "method" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "uri" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "ip" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "version" varchar(255) COLLATE "pg_catalog"."default" DEFAULT NULL::character varying,
  "create_time" timestamp(6) DEFAULT NULL::timestamp without time zone
)
;
COMMENT ON COLUMN "public"."log_error_info"."id" IS '主键id';
COMMENT ON COLUMN "public"."log_error_info"."req_param" IS '请求参数';
COMMENT ON COLUMN "public"."log_error_info"."name" IS '异常名称';
COMMENT ON COLUMN "public"."log_error_info"."message" IS '异常信息';
COMMENT ON COLUMN "public"."log_error_info"."user_id" IS '操作用户id';
COMMENT ON COLUMN "public"."log_error_info"."user_name" IS '操作用户名称';
COMMENT ON COLUMN "public"."log_error_info"."method" IS '请求方法';
COMMENT ON COLUMN "public"."log_error_info"."uri" IS '请求url';
COMMENT ON COLUMN "public"."log_error_info"."ip" IS '请求IP';
COMMENT ON COLUMN "public"."log_error_info"."version" IS '版本号';
COMMENT ON COLUMN "public"."log_error_info"."create_time" IS '创建时间';
COMMENT ON TABLE "public"."log_error_info" IS '操作日志异常信息';

ALTER TABLE "public"."log_error_info" ADD CONSTRAINT "log_error_info_pkey" PRIMARY KEY ("id");

二、实现

1、添加依赖

代码语言:javascript复制
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

2、操作日志注解类 Log.java

代码语言:javascript复制
package com.demo.utils.annotation;

import java.lang.annotation.*;

/**
 * @path:com.demo.utils.annotation.Log.java
 * @className:Log.java
 * @description:自定义操作日志注解
 * @author:tanyp
 * @dateTime:2021/11/18 13:53 
 * @editNote:
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

    /**
     * 操作模块
     * @return
     */
    String modul() default "";

    /**
     * 操作类型
     * @return
     */
    String type() default "";

    /**
     * 操作说明
     * @return
     */
    String desc() default "";

}

3、切面类记录操作日志 LogAspect.java

代码语言:javascript复制
package com.demo.utils.aop;

import com.alibaba.fastjson.JSON;
import com.demo.domain.LogErrorInfo;
import com.demo.domain.LogInfo;
import com.demo.service.LogErrorInfoService;
import com.demo.service.LogInfoService;
import com.demo.utils.IPUtils;
import com.demo.utils.SecurityUserUtils;
import com.demo.utils.annotation.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @path:com.demo.utils.aop.LogAspect.java
 * @className:LogAspect.java
 * @description:切面处理类,操作日志异常日志记录处理
 * @author:tanyp
 * @dateTime:2021/11/18 13:57 
 * @editNote:
 */
@Aspect
@Component
public class LogAspect {

    /**
     * 操作版本号
     * 项目启动时从命令行传入,例如:java -jar xxx.war --version=201902
     */
    @Value("${version}")
    private String version;

    /**
     * 统计请求的处理时间
     */
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private LogErrorInfoService logErrorInfoService;

    /**
     * @methodName:logPoinCut
     * @description:设置操作日志切入点 记录操作日志 在注解的位置切入代码
     * @author:tanyp
     * @dateTime:2021/11/18 14:22
     * @Params: []
     * @Return: void
     * @editNote:
     */
    @Pointcut("@annotation(com.demo.utils.annotation.Log)")
    public void logPoinCut() {
    }

    /**
     * @methodName:exceptionLogPoinCut
     * @description:设置操作异常切入点记录异常日志 扫描所有controller包下操作
     * @author:tanyp
     * @dateTime:2021/11/18 14:22
     * @Params: []
     * @Return: void
     * @editNote:
     */
    @Pointcut("execution(* com.demo.controller..*.*(..))")
    public void exceptionLogPoinCut() {
    }

    @Before("logPoinCut()")
    public void doBefore() {
        // 接收到请求,记录请求开始时间
        startTime.set(System.currentTimeMillis());
    }

    /**
     * @methodName:doAfterReturning
     * @description:正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
     * @author:tanyp
     * @dateTime:2021/11/18 14:21
     * @Params: [joinPoint, keys]
     * @Return: void
     * @editNote:
     */
    @AfterReturning(value = "logPoinCut()", returning = "keys")
    public void doAfterReturning(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        LogInfo logInfo = LogInfo.builder().build();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();

            // 获取切入点所在的方法
            Method method = signature.getMethod();

            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();

            // 获取操作
            Log log = method.getAnnotation(Log.class);
            if (Objects.nonNull(log)) {
                logInfo.setModule(log.modul());
                logInfo.setType(log.type());
                logInfo.setMessage(log.desc());
            }

            logInfo.setId(UUID.randomUUID().toString());
            logInfo.setMethod(className   "."   method.getName()); // 请求的方法名
            logInfo.setReqParam(JSON.toJSONString(converMap(request.getParameterMap()))); // 请求参数
            logInfo.setResParam(JSON.toJSONString(keys)); // 返回结果
            logInfo.setUserId(SecurityUserUtils.getUser().getId()); // 请求用户ID
            logInfo.setUserName(SecurityUserUtils.getUser().getUsername()); // 请求用户名称
            logInfo.setIp(IPUtils.getIpAddress(request)); // 请求IP
            logInfo.setUri(request.getRequestURI()); // 请求URI
            logInfo.setCreateTime(LocalDateTime.now()); // 创建时间
            logInfo.setVersion(version); // 操作版本
            logInfo.setTakeUpTime(System.currentTimeMillis() - startTime.get()); // 耗时
            logInfoService.save(logInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @methodName:doAfterThrowing
     * @description:异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
     * @author:tanyp
     * @dateTime:2021/11/18 14:23
     * @Params: [joinPoint, e]
     * @Return: void
     * @editNote:
     */
    @AfterThrowing(pointcut = "exceptionLogPoinCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();

            // 获取切入点所在的方法
            Method method = signature.getMethod();

            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();

            logErrorInfoService.save(
                    LogErrorInfo.builder()
                            .id(UUID.randomUUID().toString())
                            .reqParam(JSON.toJSONString(converMap(request.getParameterMap()))) // 请求参数
                            .method(className   "."   method.getName()) // 请求方法名
                            .name(e.getClass().getName()) // 异常名称
                            .message(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())) // 异常信息
                            .userId(SecurityUserUtils.getUser().getId()) // 操作员ID
                            .userName(SecurityUserUtils.getUser().getUsername()) // 操作员名称
                            .uri(request.getRequestURI()) // 操作URI
                            .ip(IPUtils.getIpAddress(request)) // 操作员IP
                            .version(version) // 版本号
                            .createTime(LocalDateTime.now()) // 发生异常时间
                            .build()
            );
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    /**
     * @methodName:converMap
     * @description:转换request 请求参数
     * @author:tanyp
     * @dateTime:2021/11/18 14:12
     * @Params: [paramMap]
     * @Return: java.util.Map<java.lang.String, java.lang.String>
     * @editNote:
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * @methodName:stackTraceToString
     * @description:转换异常信息为字符串
     * @author:tanyp
     * @dateTime:2021/11/18 14:12
     * @Params: [exceptionName, exceptionMessage, elements]
     * @Return: java.lang.String
     * @editNote:
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet   "<br/>");
        }
        String message = exceptionName   ":"   exceptionMessage   "<br/>"   strbuff.toString();
        return message;
    }
}

4、实体类

4.1、LogInfo.java

代码语言:javascript复制
package com.demo.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * @path:com.demo.domain.LogInfo.java
 * @className:LogInfo.java
 * @description:操作日志信息
 * @author:tanyp
 * @dateTime:2021/11/18 11:33 
 * @editNote:
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "log_info")
public class LogInfo {

    // 主键id
    @TableId(type = IdType.ASSIGN_UUID)
    private String id;

    // 功能模块
    private String module;

    // 操作类型
    private String type;

    // 操作描述
    private String message;

    // 请求参数
    private String reqParam;

    // 响应参数
    private String resParam;

    // 耗时
    private Long takeUpTime;

    // 操作用户id
    private String userId;

    // 操作用户名称
    private String userName;

    // 操作方法
    private String method;

    // 请求url
    private String uri;

    // 请求IP
    private String ip;

    // 版本号
    private String version;

    // 创建时间
    private LocalDateTime createTime;

}

4.2、LogErrorInfo.java

代码语言:javascript复制
package com.demo.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * @path:com.demo.domain.LogErrorInfo.java
 * @className:LogErrorInfo.java
 * @description:操作日志异常信息
 * @author:tanyp
 * @dateTime:2021/11/18 11:33 
 * @editNote:
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "log_error_info")
public class LogErrorInfo {

    // 主键id
    @TableId(type = IdType.ASSIGN_UUID)
    private String id;

    // 请求参数
    private String reqParam;

    // 异常名称
    private String name;

    // 异常信息
    private String message;

    // 操作用户id
    private String userId;

    // 操作用户名称
    private String userName;

    // 请求方法
    private String method;

    // 请求url
    private String uri;

    // 请求IP
    private String ip;

    // 版本号
    private String version;

    // 创建时间
    private LocalDateTime createTime;

}

5、在Controller层方法添加@Log注解

代码语言:javascript复制
@Log(modul = "日志-操作日志分页", type = Constants.SELECT, desc = "操作日志分页")
@GetMapping("/logInfoPage")
public Wrapper<IPage<LogInfo>> logInfoPage(Page page) {
    return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, logInfoService.page(page,Wrappers.<LogInfo>lambdaQuery().orderByDesc(LogInfo::getCreateTime)));
}

三、操作日志、异常日志查询功能

0 人点赞