SpringMVC 使用aop記錄用戶操作日誌


系統監控- 操作日誌 使用apo記錄用戶操作日誌
https://github.com/elunez/eladmin

 

1、添加spring配置文件

<!-- 日誌 -->
	<context:annotation-config></context:annotation-config>
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<bean id="logBean" class="com.test.sys.log.aspect.LogAspect"></bean>

 

2、配置web.xml

 監聽RequestContextListener, 獲取request

	<!--配置RequestContextListener監聽器-->
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
public class RequestHolder {

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}

 

3、定義註解

/**
 * @author jie
 * @date 2018-11-24
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
	String value() default "";
}

在登錄接口添加註解

    @Log("用戶登錄")
    @RequestMapping("login")
    public String login(User user, HttpSession session, HttpServletRequest request ) {}

 

 

4、定義攔截處理類


import com.test.base.exception.BadRequestException;
import com.test.base.utils.ThrowableUtil;
import com.test.sys.log.model.SysLog;
import com.test.sys.log.service.SysLogServiceI;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jie
 * @date 2018-11-24
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private SysLogServiceI logService;

    private long currentTime = 0L;

    /**
     * 配置切入點
     */
    @Pointcut("@annotation(com.vizhuo.sys.log.annotation.Log)")
    public void logPointcut() {
        // 該方法無方法體,主要爲了讓同類中其他方法使用此切入點
    }

    /**
     * 配置環繞通知,使用在方法logPointcut()上註冊的切入點
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint){
        Object result = null;
        currentTime = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new BadRequestException(e.getMessage());
        }
        SysLog log = new SysLog("INFO",System.currentTimeMillis() - currentTime);
        logService.add(joinPoint, log);
        return result;
    }

    /**
     * 配置異常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        SysLog log = new SysLog("ERROR",System.currentTimeMillis() - currentTime);
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        logService.add((ProceedingJoinPoint)joinPoint, log);
    }
}

 

5、存儲數據庫

@Service("SysLogService")
public class SysLogServiceImpl extends BaseServiceImpl<SysLog, SysLogQuery, Integer> implements SysLogServiceI {

    private static final Logger logger = LoggerFactory.getLogger(SysLogServiceImpl.class);


    @Autowired
    public void setSysLogMapper(SysLogMapperI sysLogMapper) {
        setBaseMapper(sysLogMapper);

    }

    private final String LOGINPATH = "login";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ProceedingJoinPoint joinPoint, SysLog log) {

        // 獲取request
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);

        // 描述
        if (log != null) {
            log.setDescription(aopLog.value());
        }

        // 方法路徑
        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        if ("com.test.sys.log.controller.SysLogController.findEntityByPager()".equals(methodName)) {
            return;
        }

        //參數值
        Object[] argValues = joinPoint.getArgs();
        //參數名稱
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();


        if (argValues != null) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("{");
            for (int i = 0; i < argValues.length; i++) {
                buffer.append(" " + argNames[i] + ": " + argValues[i]);
            }
            buffer.append(" }");
            String params = buffer.toString();
            log.setParams(params);

            logger.info(" params............" + params.length());
        }

        // 獲取IP地址
        log.setRequestIp(RequestHolder.getIP(request));

//        if(!LOGINPATH.equals(signature.getName())){
//            username = SecurityUtils.getAccount();
//        } else {
//            try {
//                JSONObject jsonObject = new JSONObject(argValues[0]);
//                username = jsonObject.get("username").toString();
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }

        String account = SecurityUtils.getAccount();
        log.setMethod(methodName);
        log.setAccount(account);


        logger.info(" save log............");
        SysLogMapperI rm = (SysLogMapperI) baseMapper;
        rm.insertEntity(log);
    }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章