1. 程式人生 > >springboot使用aop實現操作日誌

springboot使用aop實現操作日誌

新增依賴build.gradle

compile('org.springframework.boot:spring-boot-starter-aop:1.5.10.RELEASE')

增加配置

spring.aop.auto=true
spring.aop.proxy-target-class=true

功能程式碼

import com.datbc.youpinchain.admin.service.AdminTokenManager;
import com.datbc.youpinchain.admin.util.IpUtil;
import com.datbc.youpinchain.db.domain.ManagerLog;
import com.datbc.youpinchain.db.repository.LogRepo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Resource
    LogRepo logRepo;

    @Resource
    private AdminTokenManager adminTokenManager;

    /**
     * 管理員登入方法的切入點
     */
    @Pointcut("execution(public * com.datbc.youpinchain.admin.web.AuthController.login(..))")
    public void loginCell() {
    }

    /**
     * 新增業務邏輯方法切入點
     */
    @Pointcut("execution(* com.datbc.youpinchain.admin.web.*.create*(..))")
    public void insertCell() {
    }

    /**
     * 修改業務邏輯方法切入點
     */
    @Pointcut("execution(* com.datbc.youpinchain.admin.web.*.update*(..))")
    public void updateCell() {
    }

    /**
     * 刪除業務邏輯方法切入點
     */
    @Pointcut("execution(* com.datbc.youpinchain.admin.web.*.delete*(..))")
    public void deleteCell() {
    }

    /**
     * 登入操作(後置通知)
     *
     * @param joinPoint joinPoint
     * @param object    返回值
     */
    @AfterReturning(value = "loginCell()", returning = "object")
    public void loginLog(JoinPoint joinPoint, Object object) {
        log(joinPoint, object, ManagerLog.Operation.LOGIN.getCode());
    }

    /**
     * 新增操作日誌(後置通知)
     *
     * @param joinPoint joinPoint
     * @param object    返回值
     */
    @AfterReturning(value = "insertCell()", returning = "object")
    public void insertLog(JoinPoint joinPoint, Object object) {
        log(joinPoint, object, ManagerLog.Operation.INSERT.getCode());
    }

    /**
     * 管理員修改操作日誌(後置通知)
     *
     * @param joinPoint joinPoint
     * @param object    返回值
     */
    @AfterReturning(value = "updateCell()", returning = "object")
    public void updateLog(JoinPoint joinPoint, Object object) {
        log(joinPoint, object, ManagerLog.Operation.UPDATE.getCode());
    }

    /**
     * 刪除操作
     *
     * @param joinPoint joinPoint
     * @param object    返回值
     */
    @AfterReturning(value = "deleteCell()", returning = "object")
    public void deleteLog(JoinPoint joinPoint, Object object) {
        log(joinPoint, object, ManagerLog.Operation.DELETE.getCode());
    }


    private void log(JoinPoint joinPoint, Object object, String operation) {
        try {
            if (joinPoint.getArgs() == null) {// 沒有引數
                return;
            }
            Map map = (Map) object;
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            Integer adminId = getAdminId(joinPoint.getArgs());
            String methodRoot = joinPoint.getSignature().getDeclaringTypeName();
            String method = methodRoot + "." + joinPoint.getSignature().getName();
            String parameter = Arrays.toString(joinPoint.getArgs());
            String ip = IpUtil.getIpAddr(request);
            Integer errno = (Integer) map.get("errno");
            String errmsg = (String) map.get("errmsg");
            Object data = map.get("data");
            Gson gson = new Gson();
            String s = gson.toJson(data);

            //adminId為空判斷是登陸資訊
            if (adminId == null && data != null) {
                adminId = getAdminId(data.toString());
            }

            ManagerLog managerLog = new ManagerLog();
            managerLog.setAdminId(adminId);
            managerLog.setOperation(operation);
            managerLog.setMethod(method);
            managerLog.setMethodName(managerLog.methodRootToName(methodRoot));
            managerLog.setParameter(parameter);
            managerLog.setIp(ip);
            managerLog.setErrno(errno);
            managerLog.setErrmsg(errmsg);
            managerLog.setData(s);
            logRepo.add(managerLog);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private Integer getAdminId(Object[] args) {
        if (args == null) {
            return null;
        }
        try {
            return (Integer) args[0];
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    private Integer getAdminId(String token) {
        return adminTokenManager.getUserId(token);
    }
}