springboot 使用AOP进行操作日志处理

1.在做项目的时候有这样的需求可以记录每个用户在登录之后都干了什么,要是有人不小心删除了东西这样就有点不好了,总要记录一下是谁干的吧

所以就有了日志

第一步:添加依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

第二步:在配置文件yml中添加配置

#启用aop
spring:
  aop:
    proxy-target-class: true
    auto: true

第三步:自定义一个注解

package com.cmbchina.ccd.itpm.controller;

import com.cmbchina.ccd.itpm.entity.BusinessType;

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.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemControllerLog {
    String title()  default "";//模块
    BusinessType businessType() default BusinessType.OTHER;
    /**
     * 是否保存请求的参数
     */
    boolean isSaveRequestData() default true;
}

 第四步:记录日志信息

package com.cmbchina.ccd.itpm.aspect;

import com.cmbchina.ccd.itpm.controller.SystemControllerLog;
import com.cmbchina.ccd.itpm.entity.OperLog;
import com.cmbchina.ccd.itpm.entity.User;
import com.cmbchina.ccd.itpm.enums.BusinessStatus;
import com.cmbchina.ccd.itpm.service.OperLogService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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


@Aspect
@Component
@SuppressWarnings("all")//抑制所有的警告
public class SystemLogAspect {
    @Autowired
    public SystemLogAspect(OperLogService operLogService) {
        this.operLogService = operLogService;
    }
//    切点
    @Pointcut("@annotation(com.cmbchina.ccd.itpm.controller.SystemControllerLog)")
    public void logPointCut() {
    }

    private final OperLogService operLogService;

    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    public void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            SystemControllerLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            User currentUser = (User) request.getSession().getAttribute("user");
            OperLog operLog = new OperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            String ip = request.getRemoteAddr();
            operLog.setOperIp(ip);
            operLog.setOperUrl(request.getRequestURI());
            if (currentUser != null) {
                operLog.setOperName(currentUser.getName());
                if (currentUser.getDeptName() != null && !currentUser.getDeptName().equals("")) {
                    operLog.setDeptName(currentUser.getDeptName());
                }
            }
            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            operLog.setOperTime(new Date());
            getControllerMethodDescription(controllerLog, operLog, request);
            operLogService.save(operLog);
        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    public void getControllerMethodDescription(SystemControllerLog log, OperLog operLog, HttpServletRequest request)
            throws Exception {
        operLog.setBusinessType(log.businessType().ordinal());
        operLog.setTitle(log.title());
        if (log.isSaveRequestData()) {
            setRequestValue(operLog, request);
        }
    }

    private void setRequestValue(OperLog operLog, HttpServletRequest request) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        ObjectMapper objectMapper = new ObjectMapper();
        String params = objectMapper.writeValueAsString(map);
        operLog.setOperParam(StringUtils.substring(params, 0, 255));
    }

    private SystemControllerLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(SystemControllerLog.class);
        }
        return null;
    }
}

第五步:开始使用在controller中使用自定义注解

原文地址:https://www.cnblogs.com/blackCatFish/p/10972044.html